How to read if a checkbox is checked in PHP?
Let your html for your checkbox will be like
<input type="checkbox" name="check1">
Then after submitting your form you need to check like
if (isset($_POST['check1'])) {
// Checkbox is selected
} else {
// Alternate code
}
Assuming that check1
should be your checkbox name.And if your form submitting method is GET
then you need to check with $_GET
variables like
if (isset($_GET['check1'])) {
// Checkbox is selected
}
When using checkboxes as an array:
<input type="checkbox" name="food[]" value="Orange">
<input type="checkbox" name="food[]" value="Apple">
You should use in_array()
:
if(in_array('Orange', $_POST['food'])){
echo 'Orange was checked!';
}
Remember to check the array is set first, such as:
if(isset($_POST['food']) && in_array(...
Well, the above examples work only when you want to INSERT a value, not useful for UPDATE different values to different columns, so here is my little trick to update:
//EMPTY ALL VALUES TO 0
$queryMU ='UPDATE '.$db->dbprefix().'settings SET menu_news = 0, menu_gallery = 0, menu_events = 0, menu_contact = 0';
$stmtMU = $db->prepare($queryMU);
$stmtMU->execute();
if(!empty($_POST['check_menus'])) {
foreach($_POST['check_menus'] as $checkU) {
try {
//UPDATE only the values checked
$queryMU ='UPDATE '.$db->dbprefix().'settings SET '.$checkU.'= 1';
$stmtMU = $db->prepare($queryMU);
$stmtMU->execute();
} catch(PDOException $e) {
$msg = 'Error: ' . $e->getMessage();}
}
}
<input type="checkbox" value="menu_news" name="check_menus[]" />
<input type="checkbox" value="menu_gallery" name="check_menus[]" />
....
The secret is just update all VALUES first (in this case to 0), and since the will only send the checked values, that means everything you get should be set to 1, so everything you get set it to 1.
Example is PHP but applies for everything.
Have fun :)
You can do it with the short if:
$check_value = isset($_POST['my_checkbox_name']) ? 1 : 0;
or with the new PHP7 Null coalescing operator
$check_value = $_POST['my_checkbox_name'] ?? 0;
You can check the corresponding value as being set and non-empty in either the $_POST or $_GET array depending on your form's action.
i.e.: With a POST form using a name
of "test" (i.e.: <input type="checkbox" name="test">
, you'd use:
if(isset($_POST['test']) {
// The checkbox was enabled...
}
<?php
if (isset($_POST['add'])) {
$nama = $_POST['name'];
$subscribe = isset($_POST['subscribe']) ? $_POST['subscribe'] : "Not Checked";
echo "Name: {$nama} <br />";
echo "Subscribe: {$subscribe}";
echo "<hr />";
}
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST" >
<input type="text" name="name" /> <br />
<input type="checkbox" name="subscribe" value="news" /> News <br />
<input type="submit" name="add" value="Save" />
</form>