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


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

好的,所以我有一个带有 1 个输入和一个提交按钮的表单。现在我正在使用 if/else 语句为该输入提供三个可接受的答案。是的,不是,或者别的什么。如果/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请求上被执行。