我已经尝试了几天来弄清楚这一点,但在我运行测试场景时无法正确解决问题。基本上,这是在编辑表单上,所以它是从数据库中提取存储的值。我让它保存为"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值,然后显示会话值是否改变?
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" />