I am getting an "Undefined index" error when submitting a form with an un-checked checkbox. Is there any other way besides running an "isset" or "empty" check on each individual posted value?
I have looked at this Question and am having trouble believing that this is the only solution.
Below is some example code: EDIT: please not that these are not the actual names of the tables columns; they are named uniquely (like "postAddress, displayPhone, student, etc.)
You could write a function that checks whether a checkbox was checked:
function checkbox_value($name) {
return (isset($_POST[$name]) ? 1 : 0);
}
Now call that function in your query like this:
$sql = 'UPDATE table SET '.
'checkbox1 = '. checkbox_value('checkbox1') .','.
'checkbox2 = '. checkbox_value('checkbox2') .','.
'checkbox3 = '. checkbox_value('checkbox3') .','.
'checkbox4 = '. checkbox_value('checkbox4') .','.
'checkbox5 = '. checkbox_value('checkbox5') .','. "LIMIT 1";
If you want a on/off checkbox you can write a hidden value before you write the checkbox.
<input type="hidden" name="checkbox1" value="no" />
<input type="checkbox" name="checkbox1" value="yes" />
This will always return a value, either no (default unless checkbox is checked by default) or yes.
You can validate input with the filter functions with FILTER_VALIDATE_BOOLEAN.
Its easier if you write a function for this, like formCheckbox($name), with options for values (value 'on' means checkbox is checked by default), attributes, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With