This is my form and categories comes from the database with while loop. I want to insert the checked inputs only in to database.
How can i detect which checkbox is selected ?
<form action="account.php" method="POST">
<ul class="account-info">
<li>Category1 : <input type="checkbox" value="val1" name="cat1"></li>
<li>Category2 : <input type="checkbox" value="val2" name="cat1"></li>
<li>Category3 : <input type="checkbox" value="val3" name="cat1"></li>
<!-- while continues -->
<li>Category100 : <input type="checkbox" value="val100" name="cat1"></li>
</ul>
<input type="submit" value="submit" />
</form>
In account.php
only the check boxes will be posted. As you've named them all the same though, only 1 will be posted, the last checkbox. If you want them to have the same name and come through as an array you need to add []
after the name, like this:
<input type="checkbox" value="val100" name="cat1[]">
Then in your account.php
where they are submitted you can do this:
foreach($_POST['cat1'] as $val)
{
echo "$val<br>";
}
That will echo out the values of all the checked boxes.
You can check it like that: This code will check which categories are activated assuming that your database returns categories from 0 to x
$i = 0;
while(true){
if ($_POST["cat".$i."]) {
//category activated
}
else {
//no category found -> loop ends
break;
}
$i++;
}
change the name="cat1"
to name="cat[1][]"
in your account.php
page
foreach($_POST['cat'] as $category){
foreach($category as $value){
echo $value;
}
}
First off, you have your options set up as if they were radio buttons all having the same name turning into 1 value out of the 3 possible. If you want them to be conventional checkboxes you have to give them separate names.
in your PHP you would check if the array_key_exists
for the checkbox name in question, this is how I usually translate the checkbox fields in a form to be easier to use:
<?php
$checked = array(
'cat1' => array_key_exists('cat1', $_POST),
'cat2' => array_key_exists('cat2', $_POST),
'cat3' => array_key_exists('cat3', $_POST)
);
print_r($checked);
exit;
?>