1

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 />';
?>
6
  • 3
    Try taking the 'declarations' out of the while. Each loop erases the previous content of the variables, keeping only the last one... Commented Jun 30, 2016 at 19:28
  • But, there are better ways of doing what you are trying to do... Commented Jun 30, 2016 at 19:30
  • 1
    You are wide open to SQL Injections. If you're using MySQLi or PDO (which you should since the mysql_*-functions are deprecated), you should use Prepared Statements Commented Jun 30, 2016 at 19:33
  • Or at the very least, $staffId = $_REQUEST["ID"] + 0; to force $staffId to a numeric value. Commented Jun 30, 2016 at 19:35
  • 1
    @FirstOne Taking out the declarations worked! Thanks! I am open to doing this a different way, I'm just new to PHP and don't really know how else to go about it. Commented Jun 30, 2016 at 19:37

1 Answer 1

1

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 />";
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.