PHP If / Else 语句直接进入 Else,无需等待表单输入

PHP If / Else statement going directly to the Else without waiting for form input

好的,我有一个包含 1 个输入和一个提交按钮的表单。现在我正在使用 if/else 语句为该输入做出三个可接受的答案。是的,不,或其他任何东西。这个 if/else 正在工作,因为代码在页面加载后立即踢出 else 函数。我希望在用户输入之前什么也没有,然后它会显示三个答案之一。

Welcome to your Adventure! You awake to the sound of rats scurrying  around your dank, dark cell. It takes a minute for your eyes to adjust to your surroundings. In the corner of the room you see what looks like a rusty key.
<br/>
Do you want to pick up the key?<br/>


<?php

//These are the project's variables.

$text2 = 'You take the key and the crumby loaf of bread.<br/>';

$text3 = 'You decide to waste away in misery!<br/>';

$text4 = 'I didnt understand your answer. Please try again.<br/>';

$a = 'yes';

$b = 'no';


// If / Else operators.

if(isset($_POST['senddata'])) {

    $usertypes = $_POST['name'];

}

if ($usertypes == $a){

    echo ($text2);
}

elseif ($usertypes == $b){

    echo ($text3);
}

else {

    echo ($text4);
}

?>

<form action="phpgametest.php" method="post">
         <input type="text" name="name" /><br>
         <input type="submit" name="senddata" /><br>
</form>

设置POST值时调用代码即可。这样它只会在提交表单时执行代码(又名 $_POST['senddata'] 已设置):

if(isset($_POST['senddata'])) {

    $usertypes = $_POST['name'];

    if ($usertypes == $a){

        echo ($text2);
    }

    elseif ($usertypes == $b){

        echo ($text3);
    }

    else {
        echo ($text4);
    }
}

只需将验证放在第一个 if 语句中,如下所示:

if(isset($_POST['senddata'])) {

    $usertypes = $_POST['name'];


    if ($usertypes == $a) {
        echo ($text2);

    } elseif ($usertypes == $b) {
        echo ($text3);

    }  else {
        echo ($text4);
    }

}

当您加载页面时,浏览器会发出 GET 请求,当您提交表单时,浏览器会发出 POST 请求。您可以使用以下方式查看发出的请求:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // Your form was submitted
}

将此放在您的表单处理代码周围,以防止它在 GET 请求时执行。