我有一个复选框,我希望它能够控制一个变量构造,0表示没有构造,1表示构造。并输出任何当前值,以便用户可以查看是否检查了结构。我意识到复选框不会发布"未选中"的值,而且我已经尝试了很多方法。我不确定我的逻辑哪里有缺陷。
<input name="construction" type="checkbox" id="construction" onChange="this.form.submit();" <?php if ($row_config['construction'] == 1) { echo ' checked'; } else { echo ' unchecked'; } ?>>
<?php
if ($_POST) {
// 0 = off
// 1 = on
$constr = (isset($_POST['construction']) && $_POST['construction'] == "on") ? 1 : 0;
mysql_query("UPDATE config SET construction = '$constr'") or die(mysql_error());
redirect('index.php');
}
?>
我认为问题出在向用户输出数据方面。
固定版本,谢谢大家!
<?php
require('framework/ui_framework.php');
page_protect();
$config = mysql_query("SELECT construction FROM config") or die(mysql_error());
$row_config = mysql_fetch_assoc($config);
$isChecked = false;
$constr = 0;
if(isset($_POST['construction'])){
if($_POST['construction']) {
$isChecked = true;
$constr = 1;
mysql_query("UPDATE config SET construction = '".$constr."'") or die(mysql_error());
}
} else {
$isChecked = false;
$constr = 0;
mysql_query("UPDATE config SET construction = '".$constr."'") or die(mysql_error());
}
?>
<input name="construction" type="checkbox" id="construction" onChange="this.form.submit();" <?php if($isChecked) echo "checked='checked'"; ?> value="on">
您从未设置复选框的值,因此逻辑(isset($_POST['construction']) && $_POST['construction'] == "on")
在检查$_POST['construction'] == "on"
时失败
如果只是检查复选框是否被选中,只需使用isset()
,不必担心检查值。
您实际上并没有给复选框一个值。根据下面的PHP判断,您的复选框的属性列表中似乎缺少value="on"
。此外,复选框设置中的else echo 'unchecked'
是不必要的。
试试这个
您必须使用isset($varname)检查变量
<?php
$isChecked = false;
$constr = 0;
if(isset($_POST['construction'])){
if($_POST['construction'] == 'on'){
$isChecked = true;
$constr = 1;
}
mysql_query("UPDATE config SET contruction = '$constr'") or die(mysql_error());
}
?>
<!doctype html>
<html>
<head>
</head>
<body>
<form action='test3.php' method='POST'>
<input name="construction" type="checkbox" id="construction" onChange="this.form.submit()" <?php if($isChecked) echo "checked='checked'"; ?> />
<?php
?>
</form>
</body>
</html>