dpo69086 2012-07-15 13:42
浏览 40
已采纳

阻止变量在自我调用时重置

In the following PHP code, I'm trying to generate a random number if its not already and store it in a variable called $number, also I'm taking user input and storing it in $userInput.

Every time the submit button is pressed , the same page is called again using $_SERVER['PHP_SELF'].

My problem is that I want the $number to keep its value once its set. no matter how many times the submit button is pressed, which is something that is not happening now. the $number is set every time I press submit button.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Number Guessing Game!</title>
    </head>
    <body>
        <?php 
            $userInput = $_POST['number'];
            if(!$number){
                 $number = rand(1, 500);
            }
            else{
                 echo "random number is $number <br>";
                 echo "you entered $userInput";
            }

            echo "<h3> $number </h3>"; //just to see if the number is changing everytime
       ?>
       <form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
            <input type="text" name="number" /> <input type="submit" name="Submit"
            value="Submit" />
       </form>
    </body>
</html>
  • 写回答

4条回答 默认 最新

  • dpm91915 2012-07-15 13:45
    关注

    To make your random number persist betwen page views, you'll need to use sessions

    http://www.tizag.com/phpT/phpsessions.php/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大