php - How to checked looping checkbox with array -
i have products in database this:
1 -> torch 2 -> speaker 3 -> laptop 4 -> handphone 5 -> mouse 6 -> lcd
and in edit form, id product (example : 1,3,4,5 ) have been selected, form didn't selected checkbox properly. here code :
$selected = array(1,3,4,5); foreach ($selected $val) $q=mysql_query("select * product"); while ($r=mysql_fetch_array($q)){ echo "<input type='checkbox' name='product[]'"; if ($r['id'] == $val) echo "checked"; echo"> $r[product]<br>"; }
the result id no 5 selected, should 4 products selected,,,
it because last iteration on query result when $val 5, other not checked. change loop way:
$selected=array(1,3,4,5); $q=mysql_query("select * product"); while ($r=mysql_fetch_array($q)){ $ch = in_array($r['id'], $selected)?"checked":''; echo "<input type='checkbox' name='product[]' $ch> {$r['product']}<br />"; }
btw, don't use mysql_
functions - deprecated, , removed in future. switch mysqli
or pdo
prepared statements prevent malicious code injections.
Comments
Post a Comment