0

I have a form and I'm doing input validation, so when the user inputs something wrong I generate an error message and refill all the fields the user entered.

Now, some errors popped up when I started using the php.ini file for mysql stuff, such as

Undefined index: var in file.php on line n

For a simple text input (a title) I was able to fix this fairly easily, by doing

value="<?= isset($_POST["title"]) ? $_POST["title"] : "";?>"

However, I'm also using 5 radio buttons to give a rating, like this:

value="1" <?= $_POST["grade"] == "1" ? "checked" : "" ?>
value="2" <?= $_POST["grade"] == "2" ? "checked" : "" ?>
etc

I tried applying the isset bandage here as well,

value="1" <?= isset($_POST["grade"] == "1") ? "checked" : "" ?>

but as I was quickly reminded, isset only works with variables and arrays, not booleans.

What would be an appropriate way to solve this?

9
  • Could you please try replace the <?= with <?php and try again? Commented Oct 21, 2020 at 10:45
  • who told that isset doesn't work for boolean? Commented Oct 21, 2020 at 10:45
  • 1
    @MerianosNikos If they replace <?= with <?php, it won't output anything. <?= is just a shorter way of writing <?php echo Commented Oct 21, 2020 at 10:46
  • @MagnusEriksson I just thought that maybe changed something in the php.ini that affects the short opening tags. Without a full code example, it's not that easy to help. Commented Oct 21, 2020 at 10:47
  • 1
    @MerianosNikos - The shorthand <?= is available regardless of the short open tags setting. Commented Oct 21, 2020 at 10:48

1 Answer 1

0

The first thing you have to do is check whether the variable is set or not. Then you can append your comparison with an operator.

value="1" <?= isset($_POST["grade"]) && $_POST["grade"] == "1" ? "checked" : "" ?>
Sign up to request clarification or add additional context in comments.

2 Comments

That does indeed work, thank you! I attempted something similar before but I must have gotten the syntax or order wrong.
@Robin you are frequently answering question, but I am not noticing a lot closing. Please understand that after 10 years of feverish Q&A, all basic php questions are duplicates. Please vote to close duplicate questions.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.