I want to insert whether or not a checkbox was selecting into MySQL, simply by adding 1 or 0 to the column that corresponds to the value. I am having a problem with the 0s, detailed below.
Here is an example of the checkboxes
<input type='checkbox' name='class[]' value='mathhl' id="mathhl">
For simplicity I added this
$classes = $_POST["class"];
Here is the foreach loop to check the values of the checkboxes.
foreach($classes as $value) {
if (!isset($value)) {
$value = 0;
}
else {
$value = 1;
}
echo $value;
}
For some reason, it only returns the 1s, but not 0s! I am new to PHP, so I’d like to know where exactly I’m going wrong with this, thanks!
Only checked checkboxes are sent to the server. So, if the value is not present in the array, that’s because the box wasn’t checked.
You can simplify your logic by making the values the keys in your array:
Now, you don’t have to loop over
$_POST['class']. Instead, you can take an array of the all the keys (which you should already know):And form an array with the default values (say 0):
And merge the
$_POSTarray with the defaults array:Now,
$resultswill contain an associative array, with the keys being the columns and the values being 1 or 0, depending on whether or not the checkbox was checked. Be careful, as somebody can post and data they want to$_POST, so it may not be only 1’s and 0’s.