【问题标题】:PHP: Counter using Session VariablesPHP:使用会话变量的计数器
【发布时间】:2023-03-31 18:51:01
【问题描述】:

我需要使用提交按钮向会话变量添加值的帮助。如果我将变量定义为 0,它就不会计数,如果我不这样做,它会说:

"注意:未定义索引:paperbagCount in /home/saxon/students/20151/chwi15/www/affar3/test.php 在第 52 行"

"注意:未定义索引:plasticbagCount in /home/saxon/students/20151/chwi15/www/affar3/test.php 第 59 行"

<?php 
if(!session_status() === PHP_SESSION_ACTIVE ) {
session_start();
$_SESSION["paperbagCount"] = 0;
$_SESSION["plasticbagCount"] = 0; 
} 
session_start();
error_reporting(-1);

?>

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
   <title>Startsida</title>   
</head>

<body>

<?php 
if(isset($_POST['addPaper'])) {
  $_SESSION["paperbagCount"]+=1;
}

if(isset($_POST['deletePaper'])) {
    if ($_SESSION["paperbagCount"] == 0) {
        $_SESSION["paperbagCount"] == 0; 
    }else{      
    $_SESSION["paperbagCount"]-=1;
    }
}

if(isset($_POST['addPlastic'])) {
  $_SESSION["plasticbagCount"]+=1;
}

if(isset($_POST['deletePlastic'])) {
    if ($_SESSION["plasticbagCount"] == 0) {
        $_SESSION["plasticbagCount"] == 0; 
    }else{      
    $_SESSION["plasticbagCount"]-=1;
    }
}

?>  

<form method="post">
<p><label>Paperbagcount</label><br>
<input type="submit" name="addPaper" value="+">
<?php echo $_SESSION["paperbagCount"] . "\n"; ?>
<input type="submit" name="deletePaper" value="-">
</form>

<form method="post">
<p><label>Plasticbagcount</label><br>
<input type="submit" name="addPlastic" value="+">
<?php echo $_SESSION["plasticbagCount"] . "\n"; ?>
<input type="submit" name="deletePlastic" value="-">
</form>

</body>
</html>

【问题讨论】:

标签: php variables session submit counter


【解决方案1】:

用这个替换你的 PHP 代码

<?php 
@session_start(); // @ to avoid warning
if (!isset($_SESSION["paperbagCount"])) {
    $_SESSION["paperbagCount"] = 0;
}
if (!isset($_SESSION["plasticbagCount"])) {
    $_SESSION["plasticbagCount"] = 0;
}
?>

【讨论】:

    【解决方案2】:

    session_start() 根据通过 GET 或 POST 请求或通过 cookie 传递的会话标识符创建会话或恢复当前会话。

    所以从代码中删除第二行session_start()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-22
      • 2011-09-03
      • 2016-02-29
      • 2012-08-03
      • 2013-05-01
      • 2011-06-09
      • 1970-01-01
      相关资源
      最近更新 更多