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 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?