我想编辑页面中复选框的信息,但是当我单击编辑链接时,我希望将数据库中已选择的多个复选框设置为选中状态。但是我从代码中得到的结果是,只有最后一个选中的复选框被设置为选中状态(勾选),而不是所有选中的复选框。
这是我的代码:
<td><input type = "checkbox" name = "checkbox[]" value = "Badminton" <?php if($interest == 'Badminton') echo "checked = 'checked'"; ?>/>Badminton</td>
<td><input type = "checkbox" name = "checkbox[]" value = "Baseball" <?php if($interest == 'Baseball') echo "checked = 'checked'"; ?>/>Baseball</td>
<td><input type = "checkbox" name = "checkbox[]" value = "Basketball" <?php if($interest == 'Basketball') echo "checked = 'checked'"; ?>/>Basketball</td>
<td><input type = "checkbox" name = "checkbox[]" value = "Cricket" <?php if($interest == 'Cricket') echo "checked = 'checked'"; ?>/>Cricket</td>
<td><input type = "checkbox" name = "checkbox[]" value = "Football" <?php if($interest == 'Football') echo "checked = 'checked'"; ?>/>Football</td>
这是我的sql代码:
$sql = "SELECT * FROM interest where username = '$username'";
$result = $conn->query($sql);
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
$interest = $row['interest_name'];
}
}
答案 0 :(得分:4)
首先,如果要使用查询中的所有值,则需要将它们存储在数组中,例如:
while($row = $result->fetch_assoc())
{
$interest[] = $row['interest_name'];
}
现在,当涉及到html时,您可以像这样:
<td><input type = "checkbox" name = "checkbox[]" value = "Football" <?php if(in_array('Football',$interest)) echo "checked = 'checked'"; ?>/>Football</td>
只是第一个示例,您应该在所有示例中都这样做。
答案 1 :(得分:3)
您可以将值存储到数组中,然后可以使用in_array()
进行检查:
<?php
$interest = array(); // initializing
while($row = $result->fetch_assoc())
{
$interest[] = $row['interest_name']; // store in an array
}
?>
HTML:
<td>
<input type = "checkbox" name = "checkbox[]" value = "Badminton" <?=(in_array('Badminton',$interest) ? 'checked="checked"' : '')?> />Badminton
</td>
侧面说明:将您具有的不同值更改为与上面相同的其他复选框。