为什么这种简单的递增数字代码不起作用?

时间:2019-01-12 01:17:10

标签: php session

我想对会话进行简单的递增,但是会话每次在2时都停止。您能帮我做什么吗?

 if (!isset($_SESSION["current"]))
 {
 $_SESSION["current"] = 1;
 } 
 $_SESSION["current"] = $_SESSION["current"] +1;
 echo "SESSION: ".$_SESSION["current"]."<br>CURRENT: "; 

我尝试了这段代码,但它也无法正常工作:

<?php    
if (isset($_POST["previous"]))
{
 $_SESSION["current"] = $_SESSION["current"] - 1;
}           

if (isset($_POST["next"]))
{
$_SESSION["current"] = $_SESSION["current"] + 1;
}

echo "SESSION: ".$_SESSION["current"]."<br>CURRENT: "; 
?>

2 个答案:

答案 0 :(得分:0)

该代码应该起作用,也许您的会话未处于活动状态。尝试在您的脚本之上发布此代码:

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}`

答案 1 :(得分:0)

我相信您想使用此“当前”值进行分页。如果是这种情况,那么您将犯错。请记住,会话将存储最后设置的值,直到销毁该值或将其重置为另一个值。这是我的看法

<?php   
    session_start(); // according to you, you don't need this so please remove

    $current = 0; // lowest value for our pagination

    if(isset($_SESSION['current'])){
        $current = $_SESSION['current']; // session has an entry
    }


    if ((isset($_POST["previous"]) || isset($_POST['next'])))
    {
        if(isset($_POST['previous'])){
            $current -=  1; // for previous
        }else{
            $current += 1; // for next
        }

        $current  = ($current >= 0)?$current: 0; // reset to 0 when we get to negative
    }else{
        $current = 0; // we maybe back on the "start page"               
    }           


   $_SESSION['current'] = $current;

   echo "SESSION: ".$_SESSION["current"]."<br>CURRENT: ";