Reputation: 327
I have a list of checkboxes and save the checked values in an array. However, when someone clicks 'submit' and they get an error, all their checked boxes are forgotten. Usually I would let the script remember the checked boxes with a code like
IF checkbox value = OK { echo checked="checked"}
However, now I save it in an array and I have no idea how to do this?
<?php
$sql = "SELECT merknaam FROM merken";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo " <input type=\"checkbox\" name=\"merken[]\" value='" . $row['merknaam'] . "'> " . $row['merknaam'] . " <Br /> ";
}
?>
This is the code I use for the checkboxes. Next I display the array with this code:
$merkenstring = implode(",", $_POST['merken']);
echo $merkenstring;
Result: AC Ryan,Adidas,Agu,Cargo
I hope someone could give me a code example!
Upvotes: 1
Views: 2891
Reputation: 270795
Assuming you are posting this to the same page, and $_POST['merken']
is still available after an error, use in_array()
to test each checkbox's value against the current set in $_POST
:
while ($row = mysql_fetch_array($result)) {
// If the current value is in the $_POST['merken'] array
// and the array has been initialized...
if (isset($_POST['merken']) && is_array($_POST['merken']) && in_array($row['merknaam'], $_POST['merken'])) {
// Set the $checked string
$checked = "checked='checked'";
}
// Otherwise $checked is an empty string
else $checked = "";
// And incorporate it into your <input> tag
echo " <input $checked type=\"checkbox\" name=\"merken[]\" value='" . $row['merknaam'] . "'> " . $row['merknaam'] . " <Br /> ";
//----------------------^^^^^^^^^^
}
If this was posted to a different script, you would (as with any post value returned to a previous script) need to store the array in $_SESSION
instead and compare against $_SESSION['merken']
in your in_array()
call.
Upvotes: 1
Reputation: 28929
Assuming $row['merknaam']
is the checkbox value, and $_POST['merken']
holds an array of checked checkbox values, then you simply need to check if the value is in the array:
if (in_array($row['merknaam'], $_POST['merken'])) {
// this checkbox should be checked
}
Upvotes: 0