我正在尝试创建一个函数,当勾选复选框时返回一个布尔值(1或0)....这里没有问题。我还希望它包含一个会话变量,对于勾选的每个复选框,它会递增1。当我在提交表格后回显$ _SESSION ['counter']的值时,$ _SESSION ['counter']保持为零或我最初设置的值。谁能看到我错在哪里?非常感谢您提前提供任何帮助!
<?php
if(!isset($_SESSION))
{
session_start();
}
$_SESSION['counter']= 0;
function checkbox_boolean ($checkboxID){
$checkboxID= 0;
if(isset($_POST[$checkboxID])){
$checkboxID = 1;
$_SESSION['counter']++;
}
}
if(isset($_POST['submit'])){
echo $_SESSION['counter'];
checkbox_boolean ('slot1');
checkbox_boolean ('slot2');
checkbox_boolean ('slot3');
checkbox_boolean ('slot4');
checkbox_boolean ('slot5');
checkbox_boolean ('slot6');
checkbox_boolean ('slot7');
checkbox_boolean ('slot8');
}
?>
答案 0 :(得分:0)
您正在设置
$_SESSION['counter']= 0;
每次调用PHP脚本时为零。不管以前的情况如何,这条线总是将它重置为零。
如果它尚未存在,请将其更改为仅初始化它。像...这样的东西。
if (!isset($_SESSION['counter'])) {
$_SESSION['counter']= 0;
}
答案 1 :(得分:0)
您的代码中存在相当多的错误,请参阅建议的修改
?php
// dont need to test anything just call session_start()
session_start();
// initialise only if not already in existance
if ( !isset( $_SESSION['counter'] ) ) {
$_SESSION['counter'] = 0;
}
function checkbox_boolean ($checkboxID){
// this just destroyed whatever was passed in the $checkboxID parameter
// $checkboxID= 0;
if(isset($_POST[$checkboxID])){
// This does nothing useful
//$checkboxID = 1;
$_SESSION['counter']++;
}
}
if(isset($_POST['submit'])){
echo 'Session counter before = ' . $_SESSION['counter'];
checkbox_boolean ('slot1');
checkbox_boolean ('slot2');
checkbox_boolean ('slot3');
checkbox_boolean ('slot4');
checkbox_boolean ('slot5');
checkbox_boolean ('slot6');
checkbox_boolean ('slot7');
checkbox_boolean ('slot8');
echo 'Session counter after = ' . $_SESSION['counter'];
}
?>