php - 复选框 "checked"值与 session 和数据库值冲突 PHP

标签 php mysql session checkbox

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

我正在尝试弄清楚如何让 session 正确存储我的复选框的选择,以便如果页面上出现错误等,它会正确显示我的 session 值,但实际情况是 DB 值通常最终胜过它。

那么我如何才能先显示数据库值,然后在更改后显示 session 值呢?

这是我一直在玩的东西。

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

最佳答案

So how can I initially first display the DB value, but then display the session value if changed?

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

关于php - 复选框 "checked"值与 session 和数据库值冲突 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32172926/

相关文章:

php - json_encode 不返回任何东西

mysql - 无法使用 drupal 7 中的提要模块导入超过 200 条记录

php - 如何为现有用户更改 session cookie 域

jsp - HTTPSession 中存储的属性限制

php - 获取括号后的文本

javascript - Ajax serialize() 方法没有读取 html 表单的所有数据字段

php - 循环内循环达到内存限制

MySql用户输入限制

mysql - 许多外键约束依赖于许多表

ASP.NET:如何删除所有用户的所有 session 变量?