如何用数组检查循环复选框

How to checked looping checkbox with array

我的数据库中有这样的产品:

  1 -> torch
  2 -> speaker
  3 -> laptop
  4 -> handphone
  5 -> mouse
  6 -> lcd 

在编辑表单中,id 产品(例如:1,3,4,5)已被选中,但我的表单没有正确选中复选框。 这是我的代码:

$selected = array(1,3,4,5);

foreach ($selected as $val)
    $q=mysql_query("Select * from product");

while ($r=mysql_fetch_array($q)){
    echo "<input type='checkbox' name='product[]'";
    if ($r['id'] == $val) echo "checked"; 
    echo"> $r[product]<br>";
}

结果只选了id号5,应该是选了4个产品,,,

因为最后一次迭代查询结果是在$val为5的时候,所以其他的都没有检查。以这种方式更改循环:

$selected=array(1,3,4,5);
$q=mysql_query("Select * from product");
while ($r=mysql_fetch_array($q)){
   $ch = in_array($r['id'],  $selected)?"checked":'';
    echo "<input type='checkbox' name='product[]' $ch> {$r['product']}<br />";
}

顺便说一句,不要使用 mysql_ 函数 - 它们已被弃用,将来会被删除。使用准备好的语句切换到 mysqliPDO 以防止恶意代码注入。