我正在尝试创建一个添加游戏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会发生变化,从而使两个变量不相等.
最佳答案
尝试使用会话并存储两个随机数. 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会话,对您有很大帮助.