1

我需要根据 mysql 数据库中的值使用引导开关设置复选框的状态。

我试图用这样的 PHP 来做,但它似乎不起作用,代码是摘录:

while ($row = $result->fetch_assoc()) {

    $checkdevicestate = $row["devicestatus"];
    if ($checkdevicestate == "false") {
        $devstatus = "";
    } else if ($checkdevicestate == "true") {
        $devicestatus = "checked";
    }   

    $devicecontent .= '<tr><td style="width:60%"><span data-icon="7" class="linea-icon linea-basic fa-fw"></span>'. $row["devicename"] .'</td><td style="width:100%"><input type="checkbox" id="' . $row["devicecode"].'" '.$devicestatus.' class="devicebtn"data-on-color="info" data-size="small"data-off-color="danger"></td></tr>';
}

开关检查状态似乎是随机的,而不是基于我从数据库收到的值。

4

1 回答 1

0

代码看起来不错我只是修复比较运算符以===确定类型。

while ($row = $result->fetch_assoc()) {
    $checkdevicestate = $row["devicestatus"];
    if ($checkdevicestate === "false") {
        $devstatus = "";
    } else if ($checkdevicestate === "true") {
        $devicestatus = "checked";
    }   

    $devicecontent .= '<tr><td style="width:60%"><span data-icon="7" class="linea-icon linea-basic fa-fw"></span>'. $row["devicename"] .'</td><td style="width:100%"><input type="checkbox" id="' . $row["devicecode"].'" '.$devicestatus.' class="devicebtn"data-on-color="info" data-size="small"data-off-color="danger"></td></tr>';
}

如果您没有任何奇怪的状态,$row["devicestatus"]您甚至可以使用三元运算符

$devicestatus = ($checkdevicestate === "true") ? "checked='checked'" : '';
于 2017-04-13T11:33:09.123 回答