I’m not sure if I’m doing this the best practice way or not, it is working but I wasn’t sure if I did it right. Anyway, as background information, let’s say I have a database with one table that stores two pieces of information. The first is a varchar(255) value that stores a name. The second is a char(1) value that stores either ‘Y’ or ‘N’ to represent yes or no respectively.
I want to edit this data with a php generated form so I create a form like so (assuming I’ve already connected and pulled the information from the database):
<input type="text" name="name" value="<?php $name; ?>" /> <input type="checkbox" name="yesno" value="Y" <?php echo $checked; ?> />
I want to have the checkbox default value checked if the data read from the database is ‘Y’.
So this is my code to assign the $checked variable in the form above:
if ($row['yesno'] == 'Y') $checked = 'checked="checked"';
With the above code if the value read from the database is ‘Y’ then it will look like this:
<input type="checkbox" name="yesno" value="Y" checked="checked" />
Otherwise, if the value is ‘N’ then it will look like this:
<input type="checkbox" name="yesno" value="Y" />
Then if the user submits the form this is my code:
$yesno = mysqli_real_escape_string($link, $_POST['yesno']); if (!isset($_POST['yesno'])) $yesno = 'N'; $sql = "UPDATE table SET yesno='$yesno' WHERE id='$id'";
It all works, but did I do it the best practices way?