gpt4 book ai didi

php - "How to have the user add two random integers on a single page using $_POST"

转载 作者:搜寻专家 更新时间:2023-10-31 20:57:08 25 4
gpt4 key购买 nike

我正在尝试创建一个 PHP 和 HTML 加法游戏,用户可以在其中猜测两个随机整数的总和。然而,当用户提交答案时,整数再次随机化,改变总和并使用户的猜测不正确。

<?php
$x = (rand(1,10));
$y = (rand(1,10));
$sum = $x + $y;
if (isset($_POST['submit']))
{
$guess = $_POST['guess'];
if ($sum == $guess)
{
echo "nice, you got it right.";
}
else {
echo "aw, too bad. <br>";
}
}
echo "<br>What is " . $x . " + " . $y . "? <br>";?>

<form action="" method="post">
<input name="guess" type="text" />
<input name="submit" type="submit" />
</form>

$guess==$sum 时,我希望输出是“很好,你做对了”,但是当提交表单时 $sum 发生了变化,使 2 个变量不相等。

最佳答案

尝试使用session,存储这两个随机数。 PHP Session

就像这样。

<?php

session_start();

if (isset($_POST['submit']))
{
$sum = $_SESSION['y'] + $_SESSION['x'];
$guess = $_POST['guess'];
if ($sum == $guess)
{
echo "nice, you got it right.";
}
else {
echo "aw, too bad. <br>";
}
}
$_SESSION['x']= (rand(1,10));
$_SESSION['y']= (rand(1,10));
echo "<br>What is " . $_SESSION['x'] . " + " . $_SESSION['y'] . "? <br>";
?>

<form action="" method="post">
<input name="guess" type="text" />
<input name="submit" type="submit" />
</form>

希望我能回答你的问题。只需阅读 PHP session ,它对您有很大帮助。

关于php - "How to have the user add two random integers on a single page using $_POST",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55860408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com