dongwanqiang_2017 2014-07-20 13:07
浏览 45

如何在PHP中保留随机值,同时还使用表单提交

I have a PHP page that defines random variables using mt_rand() and then uses html forms to get two user inputs. And depending on whether the input numbers are equal to the randomised numbers outputs "correct".

However I have the problem that when I reload the page by submitting the values from the forms my randomised values change and the answers are always wrong. I have looked and found the solution of AJAX (J-Query function of stopping reloading). I haven't used Javascript before but will learn it if needed. My question is whether there is another way to go about getting the values and determining whether they are the same as my randomised values or will I need to stop the page from reloading upon submission?

My code is below:

<html>
<?php

$x1 = mt_rand(-12,12);
$x2 = mt_rand(-12,12);


echo "$x1<br>$x2<br>";

?>

<form action="es_algebra.php" method="POST">
<input type="number" name="x1"/>
<input type="number" name="x2"/>
<input type="submit" value="Submit"/>
</form>

<?php
if ($_POST['x1'] == $x1)
{
    echo "Correct";
}
else
{
    echo "Wrong";
}

?>
</html>
  • 写回答

1条回答 默认 最新

  • dtmm0148603 2014-07-20 13:10
    关注

    Store the random values in session-variables.

    <?php
    session_start();
    $x1 = mt_rand(-12,12);
    $x2 = mt_rand(-12,12);
    $_SESSION['x1'] = $x1;
    $_SESSION['x2'] = $x2;
    

    ...

    <?php
    session_start();
    if ($_POST['x1'] == $_SESSION['x1']) {
        [...]
    

    Final code:

    <?php session_start(); ?>
    <html>
    <?php
    if (!isset($_POST['submit'])) {
        // Generate random numbers
        $x1 = mt_rand(-12, 12);
        $x2 = mt_rand(-12, 12);
    
        // Store
        $_SESSION['x1'] = $x1;
        $_SESSION['x2'] = $x2;
    }
    
    // Debug output
    echo $_SESSION['x1'] . '<br />' . $_SESSION['x2'] . '<br />';
    ?>
    <form action="" method="post">
        <input type="number" name="x1"/>
        <input type="number" name="x2"/>
        <input type="submit" value="Submit" name="submit" />
    </form>
    <?php
    if (isset($_POST['submit'])) {
        if ($_POST['x1'] == $_SESSION['x1']) {
            echo 'x1 correct';
        }
        else {
            echo 'x1 wrong';
        }
    
        echo '<br />';
    
        if ($_POST['x2'] == $_SESSION['x2']) {
            echo 'x2 correct';
        }
        else {
            echo 'x2 wrong';
        }
    }
    ?>
    </html>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料