我的HTML和PHP代码没有给我预期的输出

时间:2017-12-10 05:09:50

标签: php html

我一直在尝试为猜谜游戏编写代码。用户必须猜测1-99的随机奇数。这是我的代码 -

<?php

$heading = "Welcome to the guessing game";
$num_to_guess = rand(1,99);
if(!isset($_POST['guess'])){
    $message= "Welcome to the guessing game";

} elseif($_POST['guess'] %2==0) {
    $message= "The number you are guessing is not odd!!!";

} elseif($_POST['guess']< $num_to_guess){
    $message= "Your guess is smaller than the secret number";

}elseif($_POST['guess']> $num_to_guess){
    $message= "Your guess is bigger than the secret number";

} elseif($_POST['guess']== $num_to_guess){
    $message= "You guessed correctly.Now try to guess another number!";
}

?>
<!DOCTYPE html>
<html>
<head>
<title> Guessing Machine </title>
</head>
<h1> <?php echo $message; ?></h1>
<body>
<form action="" method="POST">
<p><label for= "guess">Try to guess the odd number between 1 and 99 </label>
<input type= "text" is= "guess" name= "guess" /></p>
<br>
<input type="submit" name="check" value="Check"/><br><br>
</form>
</body>
</html>

现在我得到前四个if语句的所需输出。我该怎么做才能收到消息,“你猜对了!现在试着猜猜另一个号码!” ? 我很迷茫。如果有人可以提供帮助,那将非常有帮助。谢谢。

1 个答案:

答案 0 :(得分:0)

在php中,任何变量在页面渲染后销毁,因为你不能用通常的变量保存$num_to_guess数字。你需要设置会话并使用多个。

我将您的代码更改为:

<?php

$heading = "Welcome to the guessing game";
if (!isset($_SESSION['g_number'])){
    $_SESSION['g_number'] =  rand(1,99);
}
$num_to_guess = $_SESSION['g_number'];
if(!isset($_POST['guess'])){
    $message= "Welcome to the guessing game";

} elseif($_POST['guess'] %2==0) {
    $message= "The number you are guessing is not odd!!!";

} elseif($_POST['guess']< $num_to_guess){
    $message= "Your guess is smaller than the secret number";

}elseif($_POST['guess']> $num_to_guess){
    $message= "Your guess is bigger than the secret number";

} elseif($_POST['guess']== $num_to_guess){
    $message= "You guessed correctly.Now try to guess another number!";
    unset($_SESSION['g_number']);
}

?>