我有一个复选框,我希望能够拥有它以便控制变量构造,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">
答案 0 :(得分:2)
您永远不会为复选框设置值,因此在检查(isset($_POST['construction']) && $_POST['construction'] == "on")
时,您的逻辑$_POST['construction'] == "on"
会失败
如果只是看看是否选中了复选框,只需使用isset()
并且不用担心检查值。
答案 1 :(得分:2)
您实际上没有给复选框一个值。从PHP以下来看,您的复选框的属性列表中似乎缺少value="on"
。此外,复选框设置中的else echo 'unchecked'
是不必要的。
答案 2 :(得分:1)
试试这个
并且您必须使用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>