I have a group of checkboxes with different values each. I want to assign their values in php variables which i’m going to send to database. The main problem is that i don’t know how to check inside the php code if the values of selected items matching their default values which i setup in the html (apple == apple, samsung == samsung) and so on. This is because someone can just change the input value inside the console and insert whatever he likes in my DB. Any ideas how i can sort this out. Many thanks!
<form action="" method="POST">
<label for="apple">Apple</label>
<input id="apple" type="checkbox" name="myCheckBoxes[]" value="Apple">
<label for="samsung">Samsung</label>
<input id="samsung" type="checkbox" name="myCheckBoxes[]" value="Samsung">
<label for="lenovo">Lenovo</label>
<input id="lenovo" type="checkbox" name="myCheckBoxes[]" value="Lenovo">
<label for="google">Google Pixel</label>
<input id="google" type="checkbox" name="myCheckBoxes[]" value="Google Pixel">
<button type="submit" name="submit">Send</button>
</form>
PHP Code:
if (isset($_POST['submit'])) {
$checkBoxes = $_POST['myCheckBoxes'];
$numberSelected = count($checkBoxes);
if ($numberSelected > 3) {
echo 'Please select only 3 from the options';
} else {
for ($i = 0; $i < $numberSelected; $i++) {
$option1 = $checkBoxes[0];
$option2 = $checkBoxes[1];
$option3 = $checkBoxes[2];
}
echo 'You have selected', ' ', $option1, ' ', $option2, ' ', $option3;
}
}
2
Answers
You can define a constant array with the allowed values, then only use values from that array when they correspond to the input value.
The code above will accept
"APPLE"
but will use"Apple"
anything not found or empty will be set tonull
. Run it live here: https://onlinephp.io/c/8409eyou can do it through the help of or (||) , and (&&) operator in else part of if condition.