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?

user1901162
  • 1,017
  • 1
  • 8
  • 8

1 Answers1

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" : "" ?>
Robin Gillitzer
  • 1,603
  • 1
  • 6
  • 17
  • 1
    That does indeed work, thank you! I attempted something similar before but I must have gotten the syntax or order wrong. – user1901162 Oct 21 '20 at 10:53
  • @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. – mickmackusa Oct 21 '20 at 11:05