php 如何根据数据库中的值显示选中的复选框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4803221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How could I display a checked checkbox based from it's value in the database?
提问by shire
I'm new in PHP, could you help me solve my problem? I'm trying to display the checkbox checked based on its value in the database. I have saved its value as 1 if it's checked and 0 if it's not.
我是 PHP 新手,你能帮我解决我的问题吗?我正在尝试显示根据其在数据库中的值选中的复选框。如果选中,我将其值保存为 1,否则保存为 0。
回答by Dan Grossman
<?php
$sql = "SELECT somecol FROM sometable";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$checked = $result['somecol'];
?>
<input type="checkbox" name="somecol" value="1" <?php if ($checked == 1) echo 'checked'; ?> />
回答by RichardTheKiwi
You can test the field, let's say $row['col']
, and emit checked="checked"
if the field contains 1.
您可以测试该字段,例如$row['col']
,checked="checked"
如果该字段包含 1 ,则发出。
echo '<input type="checkbox" name="n" value="v"' . ($row['col']==1 ? ' checked="checked"' : '') . '>';