如何根据数据库中1/0的值设置表格行内复选框的勾选/未勾选状态
解决PHP拼接HTML时复选框状态判断的语法问题
我来帮你搞定这个问题~你遇到的语法错误,本质是不能直接在字符串拼接的过程中插入完整的PHP判断语句——因为你是在构建一个字符串变量$output,单引号包裹的内容会被当成纯文本,里面的PHP代码不会被解析执行,自然就报错了。
正确的解决思路
先提前计算好复选框需要的checked属性值,再把这个值拼到HTML字符串里就可以了。具体步骤如下:
- 在
while循环内部,先根据$row['Barva']的值生成对应的checked属性字符串; - 把生成好的字符串插入到
<input>标签中; - 顺便修正一下
name属性的写法,给属性值加上引号,避免潜在的HTML语法问题。
修改后的完整代码
$output = ' <br /> <table class="table table-bordered table-striped"> <tr> <th width="1%">!</th> <th width="1%">ID</th> <th width="10%">Inventární číslo</th> <th width="10%">Serial Number</th> <th width="10%">Produkt</th> <th width="10%">Oddělení</th> <th width="10%">Místnost</th> <th width="10%">IP</th> <th width="10%">Síť/USB</th> <th width="10%">Datum</th> <th width="10%">Funkce</th> </tr> '; while($row = mysqli_fetch_array($result)) { // 先判断并生成checked属性 $checked = $row['Barva'] == 1 ? 'checked="checked"' : ''; // 修正name属性的引号,同时加入$checked变量 $output .= ' <tr> <td contenteditable="false"><form method="post"><input type="checkbox" name="checkbox'.$row['ID'].'" '.$checked.'></form></td> <td contenteditable="true">'.$row["ID"].'</td> <td contenteditable="true">'.$row["Inventárníčíslo"].'</td> <td contenteditable="true" class="jmeno">'.$row["SerialNumber"].'</td> <td contenteditable="true">'.$row["Produkt"].'</td> <td contenteditable="true">'.$row["Oddělení"].'</td> <td contenteditable="true" class="jmeno">'.$row["Místnost"].'</td> <td contenteditable="true">'.$row["IP"].'</td> <td contenteditable="true">'.$row["USB"].'</td> <td contenteditable="true">'.$row["Datum"].'</td> </tr> '; } $output .= '</table>'; echo $output; ?>
额外提示
- 访问数组元素时,建议用带引号的索引(比如
$row['ID']而不是$row[ID]),避免PHP把ID当成常量解析,引发不必要的警告; - 如果你的PHP版本支持,也可以用双引号字符串插值的写法,代码会更简洁,比如:
$output .= " <tr> <td contenteditable=\"false\"><form method=\"post\"><input type=\"checkbox\" name=\"checkbox{$row['ID']}\" {$checked}></form></td> ... </tr> ";
不过要注意转义双引号里的双引号,或者用 heredoc 语法来写,可读性会更好。
内容的提问来源于stack exchange,提问作者user15791975
相关产品推荐
相关产品推荐

