复选框"已检查"值与会话和DB值的冲突PHP

时间:2015-08-24 00:28:18

标签: php mysql session checkbox

我已经尝试了几天来解决这个问题,但是在我测试方案的过程中无法正常运行。基本上,这是在编辑表单上,因此它从数据库中提取存储的值。我把它保存为" 1"或者" 0",1被检查。它也是一个复选框,而不是一个数组。

我试图找出如何使会话正确存储我的复选框的选择,以便如果页面上出现错误等,它会正确显示我的会话值,但会发生什么是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" />

1 个答案:

答案 0 :(得分:0)

  

那么我怎样才能首先显示数据库值,然后显示   会话值如果改变了吗?

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" />