Search code examples
phpisset

PHP, undefined index, isset and radio buttons


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?


Solution

  • 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" : "" ?>