如何在两次发布后保持 select 的价值?

How to keep value of select after two posts?

我的网站上有一个选择框和一组单选按钮。我想在更改单选按钮后保留选择框的值。我已经设法将值保留在选择框中,但是当我按下另一个单选按钮时,出现此错误

“注意:未定义的索引:第 11 行的 checkGame

注意:未定义索引:第 13 行的 checkGame

这是我的代码:

    if(isset($_POST['submit']) && $_POST['checkGame'] != 'Any')
    {
        $game = $_POST['checkGame'];
        $sql="SELECT ipaddress, port FROM servers WHERE game=('$game')";
        $result=mysqli_query($con,$sql);
            $result=mysqli_query($con,$sql);
            while ($row=mysqli_fetch_array($result)) {
            array_push($serverConnectionArray, ["address" =>$row['ipaddress'], "port" =>$row['port']]);
    }
    }
    if(isset($_POST['playersSort']))
    {
        if($_POST['playersSort'] == 'Players Descending')
        {
              uasort($serverArray, function($a, $b) {
                return $b['Players'] <=> $a['Players'];
                });  
        }
        if($_POST['playersSort'] == 'Players Ascending')
        {
              uasort($serverArray, function($a, $b) {
                return $a['Players'] <=> $b['Players'];
                });  
        }
        if($_POST['playersSort'] == 'Max Players Descending')
        {
              uasort($serverArray, function($a, $b) {
                return $b['MaxPlayers'] <=> $a['MaxPlayers'];
                });  
        }
                    if($_POST['playersSort'] == 'Max Players Ascending')
        {
              uasort($serverArray, function($a, $b) {
                return $a['MaxPlayers'] <=> $b['MaxPlayers'];
                });  
        }
    }

    <form method="post">
    Game:
    <select name="checkGame">
        <option value="Any"<?php if (isset($game) && $game=="Any") echo "selected";?>>Any</option>
        <option value="Garrys Mod"<?php if (isset($game) && $game=="Garrys Mod") echo "selected";?>>Garrys Mod</option>
        <option value="Counter Strike Global Offensive"<?php if (isset($game) && $game=="Counter Strike Global Offensive") echo "selected";?>>Counter Strike Global Offensive</option>
        <option value="Counter Strike Source"<?php if (isset($game) && $game=="Counter Strike Source") echo "selected";?>>Counter Strike Source</option>
        <option value="Team Fortress 2"<?php if (isset($game) && $game=="Team Fortress 2") echo "selected";?>>Team Fortress 2</option>
    </select>
    <input type="submit" name="submit" value="Filter"/>
    </form>

    <form action="" method="post">
        <input type="radio" name="playersSort" value="Players Descending">Players Descending
        <input type="radio" name="playersSort" value="Players Ascending">Players Ascending
        <input type="radio" name="playersSort" value="Max Players Descending">Max Players Descending
        <input type="radio" name="playersSort" value="Max Players Ascending">Max Players Ascending
        <input type="submit" name="submit" value="Sort" />
    </form>

问题出在这一行:

<input type="submitSort" name="submit" value="Sort" />

您将提交按钮设置为 submitSort 类型,而它应该是 submit

您可以使用 name 字段更改提交的名称,但类型必须是 submit 才能像提交按钮一样工作

我还建议在 post

之后使用 $_SESSION 变量来存储内容

这是一个简单的例子:

这可能不是最好的方法,它是为了展示概念(请进行任何修正编辑)

    $_SESSION['game'] = "";
    
    if(isset($_POST['submit']) && $_POST['checkGame'] != 'Any')
    {
        $_SESSION['game'] = $_POST['checkGame'];
    }

    if ($_SESSION['game'] == "1") { $gameCOD = "selected"; } else $gameCOD = "";
    if ($_SESSION['game'] == "2") { $gameBAT = "selected"; } else $gameBAT = "";
    
    <form method="post">
    <select name="checkGame">
        <option value="1">Any</option>
        <option value="2" <?php echo $gameCOD; ?> > COD </option>
        <option value="3" <?php echo $gameBAT; ?> > BATTLEFIELD </option>
    </select>
    <input type="submit" name="submit" value="Filter"/>
    </form>

在看了一会儿代码并提到需要防止 sql 注入之后,我花了一个小时左右的时间将以下内容拼凑在一起 - 最初代码只是为了展示如何使用 [= =11=] 但最终变成了你在下面看到的样子。 None 其中已经过测试,因此可能会出现语法错误 - 我怀疑它们会变得很明显。

在我看来,拥有两种形式似乎毫无意义 - 所以它们已在此处合并,并且 sort 单选按钮有一个值为零的隐藏字段 - 这里的想法是,如果没有单选按钮选择按钮然后将始终提交零值 - 这在处理 POST 数组时很有用。

每个游戏的名称在任何处理完成之前都在数组中定义 - 这允许检查 POSTed 值是否有效,还允许 SELECT 菜单选项和 RADIO 按钮动态生成 - 当与 SESSION 变量 ('game' & 'sort') 结合使用时,无论按下哪个按钮,都可以实现记住先前提交的值的最初目标。

<?php

    session_start();



    /*
        include database connection script or define here
    */

    $dbhost =   'localhost';
    $dbuser =   'root'; 
    $dbpwd  =   'xxx'; 
    $dbname =   'xxx';
    $db     =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );




    if( !isset( $_SESSION['game'] ) )$_SESSION['game']=false;
    if( !isset( $_SESSION['sort'] ) )$_SESSION['sort']=false;


    $games=array(
        'Any',
        'Garrys Mod',
        'Counter Strike Global Offensive',
        'Counter Strike Source',
        'Team Fortress 2'
    );
    $sorts=array(
        0,
        'Players Descending',
        'Players Ascending',
        'Max Players Descending',
        'Max Players Ascending'
    );

    $svrconn=array();



    if( $_SERVER['REQUEST_METHOD']=='POST' ){


        if( isset( $_POST['submit'], $_POST['checkGame'], $_POST['playersSort'] ) && $_POST['checkGame'] != 'Any' ){
            try{

                $game = filter_input( INPUT_POST, 'checkGame', FILTER_SANITIZE_STRING );
                if( !in_array( $game, $games ) ) throw new Exception('Unknown game');

                $_SESSION['game']=$game;

                /* create the sql statement with a placeholder `?` */
                $sql  = 'select `ipaddress`, `port` from `servers` where `game`=?';

                /* Attempt to create the `prepared statement` */
                $stmt = $db->prepare( $sql );

                /* statement was successfully created */
                if( $stmt ){

                    /* bind a variable to the placeholder & execute query */
                    $stmt->bind_param( 's', $game );
                    $result=$stmt->execute();

                    /* Yay! There are results to process */
                    if( $result ){

                        $stmt->store_result();
                        $stmt->bind_result( $ip, $port );

                        while( $rs=$stmt->fetch() ){
                            $svrconn[]=array( 'address'=>$ip, 'port'=>$port );
                        }

                        $stmt->free_result();
                        $stmt->close();
                        $db->close();

                    } else {/* bogus - no results */
                        throw new Exception('No results');
                    }
                } else {
                    throw new Exception('sql query failed to prepare');
                }
            }catch( Exception $e ){
                exit( $e->getMessage() );
            }
        }

        /*
            Because of the hidden field with a value of `0` this will not be invoked
            unless a radio button is selected.
        */
        if( !empty( $_POST['playersSort'] ) ){
            try{

                $sort=filter_input( INPUT_POST, 'playersSort', FILTER_SANITIZE_STRING );
                if( !in_array( $sort, $sorts ) ) throw new Exception('Unknown sort');
                $_SESSION['sort']=$sort;


                /*

                    presumably the array ( $svrconn ~ originally $serverConnectionArray or $serverArray? )
                    is used elsewhere in the page to display content???


                    apply filter/sorting algorithms 
                */
                switch( strtolower( $sort ) ){
                    case 'players descending':
                        uasort( $svrconn, function($a,$b) {
                            return $b['Players'] <=> $a['Players'];

                        }); 
                    break;
                    case 'players ascending':
                        uasort( $svrconn, function($a,$b) {
                            return $a['Players'] <=> $b['Players'];
                        });
                    break;
                    case 'max players descending':
                        uasort( $svrconn, function($a,$b) {
                            return $b['MaxPlayers'] <=> $a['MaxPlayers'];
                        });
                    break;
                    case 'max players ascending':
                        uasort( $svrconn, function($a,$b) {
                            return $a['MaxPlayers'] <=> $b['MaxPlayers'];
                        });
                    break;
                }
            }catch( Exception $e ){
                exit( $e->getMessage() );
            }
        }
    }

?>


<!doctype html>
<html>
    <head>
        <meta charset='utf-8' />
        <title>Games n stuff</title>
    </head>
    <body>
        <form method='post'>
            <fieldset>
                Game:
                <select name='checkGame'>
                <?php

                    $html=array();
                    foreach( $games as $value ){
                        $selected=trim( strtolower( $_SESSION['game'] ) )==trim( strtolower( $value ) ) ? 'selected=true' : '';
                        $html[]="<option value='$value' $selected>$value";
                    }
                    echo implode( PHP_EOL, $html );
                ?>
                </select>
                <input type='submit' name='submit' value='Filter' />
            </fieldset>

            <fieldset>
                <?php

                    $html=array();
                    foreach( $sorts as $value ){
                        $checked=( trim( strtolower( $_SESSION['sort'] ) )==trim( strtolower( $value ) ) ) ? 'checked' : '';

                        /* 
                            having a hidden field means `playersSort` 
                            will always be present in POSTed data 
                            ( unless someone is deliberately hijacking the form ) 
                        */
                        if( empty( $value ) )$html[]="<input type='hidden' name='playersSort' value='$value' />";
                        else $html[]="<input type='radio' name='playersSort' value='$value' $checked>$value";
                    }
                    echo implode( PHP_EOL, $html );
                ?>

                <input type='submit' name='submit' value='Sort' />
            </fieldset>
        </form>
    </body>
</html>