我想编辑页面中复选框的信息,但是当我单击编辑链接时,我希望将数据库中已选中的多个复选框设置为已选中。但是我从我的代码中得到的结果是只有最后一个选中的复选框被设置为选中(勾选)而不是所有选中的复选框。
这是我的代码:
<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'];
}
}
最佳答案
首先,如果您想使用来自查询的所有值,您需要将它们存储在一个数组中,例如:
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>
只是第一个例子,你应该在所有的例子中都这样做。
关于php - 如何根据数据库结果将多个 PHP 复选框设置为选中状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54905229/