php - 如何根据数据库结果将多个 PHP 复选框设置为选中状态?

标签 php mysql arrays loops mysqli

我想编辑页面中复选框的信息,但是当我单击编辑链接时,我希望将数据库中已选中的多个复选框设置为已选中。但是我从我的代码中得到的结果是只有最后一个选中的复选框被设置为选中(勾选)而不是所有选中的复选框。

这是我的代码:

<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/

相关文章:

php - 使用Eloquent获取模型子类型的实例

mysql - 添加 where 子句后计数查询停止正常工作

javascript - 我怎样才能做对象数组

安卓文字大小

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

PHP-mysql_fetch_array 不返回任何内容

php - 通知 : Undefined index: when calling a cookie that is set

php - 插入新行时移动 mysql 行?

mysql - 用自连接替换嵌套选择查询

javascript - JavaScript 数组实际上是作为数组实现的吗?