【问题标题】:PHP If / Else statement going directly to the Else without waiting for form inputPHP If / Else 语句直接进入 Else 无需等待表单输入
【发布时间】:2015-01-13 17:29:00
【问题描述】:

好的,我有一个带有 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>

【问题讨论】:

    标签: php if-statement


    【解决方案1】:

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

    if(isset($_POST['senddata'])) {
    
        $usertypes = $_POST['name'];
    
        if ($usertypes == $a){
    
            echo ($text2);
        }
    
        elseif ($usertypes == $b){
    
            echo ($text3);
        }
    
        else {
            echo ($text4);
        }
    }
    

    【讨论】:

    • @user3680300 查看右括号}。你的先关闭,然后运行if-elseif-else,这意味着无论表单是否提交,它都会运行。您只希望它在您发送数据时运行。
    • @user3680300 不看你的代码!第一个 if 语句在第二个之前关闭
    • 好的。实际上,我将整个东西封装在第一个括号中,但它不起作用……但后来我把它放到一个新标签中,它就起作用了。代码更改后刷新页面并没有什么不同。
    • 感谢大家的帮助。
    • @user3680300 该页面可能只是在缓存中并且正在加载旧页面。没问题。
    【解决方案2】:

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

    if(isset($_POST['senddata'])) {
    
        $usertypes = $_POST['name'];
    
    
        if ($usertypes == $a) {
            echo ($text2);
    
        } elseif ($usertypes == $b) {
            echo ($text3);
    
        }  else {
            echo ($text4);
        }
    
    }
    

    【讨论】:

    • 你也有同样的想法(我只是快了几秒钟)......呵呵呵呵。
    • @SpencerWieczorek 更快和正确的获胜者:D
    【解决方案3】:

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

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

    把它放在你的表单处理代码周围,以防止它在 GET 请求上被执行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-09
      • 2020-08-03
      相关资源
      最近更新 更多