if else和session - 如果出现的话怎么停止?

时间:2013-05-23 12:30:11

标签: php

我不确定我在这里做错了什么,但是在第一个“如果未设置”的下拉列表中进行选择之后,下拉列表仍显示在新的if输出上方。

一旦做出选择,它应该转到“ukset”或“uknotset”而不再显示下拉列表。

知道我做错了吗?

<?php
        session_start();

        // if unset
        if(!isset($_SESSION['grant_access'])) {$_SESSION['grant_access'] = 'unset';}
        if($_SESSION['grant_access'] == 'unset') {
            echo '<p>Make your choice</p>';
            echo '<form action="" onchange="this.submit()" method="post">';
            echo '<select name="thecountry">';
                echo '<option>Choose</option>';
                echo '<option value="hello">Hello</option>';
                echo '<option value="goodbye">Goodbye</option>';
                echo '<option value="unsure">Unsure</option>';
            echo '</select>';
            echo '</form>';
            }

        // if UK is set
        if(isset($_POST['thecountry']) && ($_POST['thecountry'] == 'hello')) {$_SESSION['grant_access'] = 'ukset';}
        if($_SESSION['grant_access'] == 'ukset') {
            echo 'welcome';
            }

        // if UK is not set
        if(isset($_POST['thecountry']) && ($_POST['thecountry'] !== 'hello')) {$_SESSION['grant_access'] = 'uknotset';}
        if($_SESSION['grant_access'] == 'uknotset') {
            echo 'access denied';
            }   

?>

2 个答案:

答案 0 :(得分:1)

这是因为您正在更改会话值的顺序。首先,将其设置为unset并显示表单。然后,在表单提交时,您的代码会运行,但由于会话变量仍为unset,因此表单再次可见。

$_POST项检查放在代码的开头,例如:

if($_SERVER['REQUEST_METHOD'] == 'POST') {
 // post check, change session value
}

// rest of the code

答案 1 :(得分:1)

你应该在选择框上执行 onchange 。检查下面的代码

<?php
    session_start();
    // if UK is set
    if(isset($_POST['thecountry']) && ($_POST['thecountry'] == 'hello')) {$_SESSION['grant_access'] = 'ukset';}
    if(@$_SESSION['grant_access'] == 'ukset') {
        echo 'welcome';
        }

                // if UK is not set
    else if(isset($_POST['thecountry']) && ($_POST['thecountry'] !== 'hello')) {$_SESSION['grant_access'] = 'uknotset';}
    if(@$_SESSION['grant_access'] == 'uknotset') {
        echo 'access denied';
        }   


    // if unset
    else if(!isset($_SESSION['grant_access'])) {$_SESSION['grant_access'] = 'unset';}
    if($_SESSION['grant_access'] == 'unset') {
        echo '<p>Make your choice</p>';
        echo '<form action="" name="frm" id="frm"  method="post">';
        echo '<select name="thecountry" onchange="frm.submit()">';
            echo '<option>Choose</option>';
            echo '<option value="hello">Hello</option>';
            echo '<option value="goodbye">Goodbye</option>';
            echo '<option value="unsure">Unsure</option>';
        echo '</select>';
        echo '</form>';
        }

&GT;