【问题标题】:Checkbox "checked" value conflict with session and DB values PHP复选框“选中”值与会话和数据库值 PHP 冲突
【发布时间】:2015-08-25 19:49:27
【问题描述】:

我已经尝试了几天来解决这个问题,但在我测试场景时无法正确解决。基本上,这是在一个编辑表单上,所以它从数据库中提取存储的值。我将它保存为“1”或“0”,1 被选中。它也是一个复选框,而不是数组。

我试图弄清楚如何使会话正确存储我的复选框的选择,以便如果页面上出现错误等,它会正确显示我的会话值,但会发生什么是 DB 值通常最终胜过了这一点。

那么我怎样才能首先显示 DB 值,然后在更改后显示会话值?

这是我一直在玩的。

if(isset($_SESSION["include_due_date"])) {                      
        $include_due_date = 'checked="checked"';                
} else {            
    if((!isset($_SESSION["include_due_date"])) && $resInvoice[0]["include_due_date"]  == 1 ) {
            $include_due_date = 'checked="checked"';
    } elseif((isset($_SESSION["include_due_date"])) && $resInvoice[0]["include_due_date"]  == 0 ) {
            $include_due_date = 'checked="checked"';
    } elseif((!isset($_SESSION["include_due_date"])) && $resInvoice[0]["include_due_date"]  == 0 ) {
            $include_due_date = '';
    }
}

有什么想法吗?

其他方法:

<input type="checkbox" value="1" <?php echo (isset($_SESSION['include_due_date'])?' checked="checked"' : (!isset($_SESSION['include_due_date'])) && $resInvoice[0]['include_due_date']  == 1?' checked="checked"' : ''); ?> name="include_due_date" id="include_due_date" />

【问题讨论】:

  • 在您提交表单并重新加载页面之前,选中该框不会更改会话中的值。首次加载时,db 值将始终优先。一个 js 解决方案可能适合您的问题。
  • 如果您没有任何form input,那么database value 就是要显示的那个。如果你有input from a form 那就是要使用的输入!。即,如果在 $_POST 中设置了复选框,则将数据库设置为 true。如果复选框 不在 $_POST 中,则将 database value 设置为 false。

标签: php mysql session checkbox


【解决方案1】:

那么我如何最初首先显示 DB 值,然后再显示 会话值是否更改?

session_start(); // (Be sure to use session_start)
// If the include_due_date was set by the session
if(isset($_SESSION["include_due_date"])) {  
    // Set the value of $checked to the value of the session variable
    // In this way, the value of the session variable takes precedence over that in the database
    $checked = ($_SESSION["include_due_date"] === true);                
} else {            
    // The session variable wasn't set, so use the value from the database to set both the checked value and the session variable.  
    // The next request will use the value from the session variable
    if($resInvoice[0]["include_due_date"] == 1 ) {
        $_SESSION["include_due_date"] = $checked = true;
    } else {
        $_SESSION["include_due_date"] = $checked = false;
    }
}

HTML

<input type="checkbox" value="1" <?php if ($checked) echo 'checked="checked"; ?> name="include_due_date" id="include_due_date" />

【讨论】:

  • 嗯,我已经可以提取 db 值并显示它了。我的问题是我需要它正确显示带有会话的复选框,但是当未选中该复选框并提交表单,然后由于故意测试错误而返回它时,它不会将复选框显示为未选中,但是而是从 db 值检查。请参阅我也尝试过的替代方法。
  • 我们缺少存储数据库和更新会话的代码。错误可能存在吗?你应该展示它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-08
  • 1970-01-01
  • 2014-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多