Reputation: 167
I am trying to generate a form with multiple checkboxes from a database. Right now only the last entry from the array is showing up. If there is supposed to be only one thing checked it works, but for more than one, only the last entry in the array shows up as checked. Any help would be greatly appreciated. Thanks!
<?php
include "DBconnect.php";
$staffId = $_REQUEST["ID"];
$query=" select listCode from staffLabels
where staffId = $staffId";
$result=$mysql->query($query);
while($row=$result->fetch_assoc()){
//in_array ()check if value is in array
$b_checked='';
$d_checked='';
$x_checked='';
$f_checked='';
$c_checked='';
if($row['listCode'] =="b") {$b_checked='checked';}
elseif($row['listCode'] =="d") {$d_checked='checked';}
elseif($row['listCode'] =="x") {$x_checked='checked';}
elseif($row['listCode'] =="f") {$f_checked='checked';}
elseif($row['listCode'] =="c") {$c_checked='checked';}
}
echo '<input type="checkbox" name="listCode[]" value="b" '.$b_checked.' >b';
echo '<input type="checkbox" name="listCode[]" value="d" '.$d_checked.' >d';
echo '<input type="checkbox" name="listCode[]" value="x" '.$x_checked.' >x';
echo '<input type="checkbox" name="listCode[]" value="f" '.$f_checked.' >f';
echo '<input type="checkbox" name="listCode[]" value="c" '.$c_checked.' >c<br /><br />';
?>
Upvotes: 1
Views: 927
Reputation: 2320
try this
<?php
include "DBconnect.php";
$staffId = (int) $_REQUEST["ID"];
$query=" select listCode from staffLabels
where staffId = $staffId";
$result=$mysql->query($query);
$checked=[];
while($row=$result->fetch_assoc()){
$checked[$row['listCode']]=true;
}
foreach(['b','d','x','f','c'] as $value){
$chk=isset($checked[$value])?'checked':'';
echo "<input type='checkbox' name='listCode[]' value='$value' $chk>";
}
echo "<br /><br />";
Upvotes: 1