PHP - 使用$ _SESSION的计数器错误

时间:2014-07-11 17:36:48

标签: php session counter

$ count ++;我正在使用if(!isset($ _ SESSION [“rand”]))...

我正在构建一个猜数游戏。

$numOfGess=4;
$min=1;
$max=10;

if(!isset($_SESSION["rand"])){
    $_SESSION["rand"] = rand($min, $max);
    $count=0;
}

if(isset($_POST["numGuess"])){
$numGuess = $_REQUEST["numGuess"];

    if($numGuess != $_SESSION["rand"]) {

        //Validation
        if($numGuess < $min || $numGuess > $max) {
            echo"Your number must be between 1 to 10 !";
        }

        //Number is Small
        if($numGuess < $_SESSION["rand"]) {
            echo "too small...";
            $count++;
        }

        //Number is Big
        if($numGuess > $_SESSION["rand"]) {
            echo "too big...";
            $count++;
        }

        if($count==$numOfGess) {
            echo"Game Over!";
            unset($_SESSION["rand"]);
        }
    }

    else {
        echo"You got it! (in your last chance)";
        unset($_SESSION["rand"]);
    }
}

3 个答案:

答案 0 :(得分:2)

您应该将count变量存储为会话变量,否则每次请求都会重置它。所以,只需用$ _SESSION ['count']替换$ count,它应该可以工作。

答案 1 :(得分:0)

在会话变量中存储计数。如果设置$ _SESSION ['rand']会发生什么?它是如何知道以前的计数是什么?

答案 2 :(得分:0)

忘记了

  

在session_start()

开始/恢复会话