我有一个复选框,我希望它能控制一个变量结构,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">发布于 2012-07-31 01:17:08
尝尝这个
并且您必须使用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>https://stackoverflow.com/questions/11725745
复制相似问题