i have a database which is composed by some field that are booleans, so in my html form i made the input type set to check box and i want to make if checked = "True", uncheck = "false".
How can i archive that ? By now if i check them i see a 0, if i don't check i don't see nothing. I have tried to put and hidden field and work with that but not getting any results.
If you need code or print screen to understand the question better please tell me. Thank you.
That's the default behavior of checkbox inputs:
so, if you have something like:
<input type="checkbox" value="TRUE" name="my_checkbox" />
In PHP, you could do something like:
if (isset($_POST["my_checkbox"])) {
echo "checkbox is checked";
} else {
echo "checkbox not checked";
}
If you want absolutely to post something even if the checkbox isn't checked, as you said, you ca use an hidden field like this:
<input type="checkbox" value="TRUE" name="my_checkbox_1" />
<input type="hidden" value="my_checkbox_1,my_checkbox_2,my_checkbox_3" name="my_checkboxes" />
the hidden field "my_checkboxes" would hold all the name of all the check boxes in your form.
Then, you can take the value of $_POST["my_checkboxes"], split the value of it (with ","), and loop through all the checkboxes:
$checkboxes = explode(",", $_POST['my_checkboxes']);
foreach($checkboxes as $checkbox) {
$checkbox_value = $_POST[$checkbox];
if (isset($checkbox_value)) {
echo "checkbox " . $checkbox . " was checked";
} else {
echo "checkbox " . $checkbox . "wasn't check";
}
}
That solution would be good if you have a dynamic form with an unknown number of checkboxes.
Posting something as "my_checkbox" ($_POST['my_checkbox']) if it is checked or not with different value would be possible with JavaScript (but I don't recommend it).
HTML Checkboxes return a value if they are checked, OR return nothing if not checked. So use isset()
HTML:
<input type="checkbox" value="1" name="chk1" />Label 1
<input type="checkbox" value="1" name="chk2" />Label 2
PHP
$chk1 = (isset($_POST['chk1']))? true : false;
$chk2 = (isset($_POST['chk2']))? true : false;