如果if语句完成,PHP表单将返回

时间:2018-12-04 18:23:11

标签: php forms if-statement

我有一些代码,希望在单击“新播放器”按钮时显示一个表单。我的问题是,当我单击表单中的“提交”按钮时,验证代码无法运行。我不确定如何强制该功能保留控制权。

原始的“新播放器”按钮调用一个外部PHP脚本

echo "<form action = '', method = 'post'>";
echo "<button  name = 'showPF', type = 'submit', value = 'New Player'>New Player</button></br>";

echo "</form>";

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


require(__DIR__.'/new_player.php');

}

然后显示该表单,并依次调用一个函数。此功能是永远不会执行的部分。

echo "<form action = '' method='post'>";
    echo "Player Name: <input type='text' name='playerName'></br>";
    echo "Character Name: <input type='text' name ='charName'></br>";
    echo "Class: <input type='text' name = 'class'></br>";
    echo "Race: <input type='text' name = 'race'></br>";
    echo "Level: <input type = 'int' name = 'level'></br>";
    echo "<button name='add', type = 'submit', value = 'Add Player'>Add Player</button></br>";
    echo "</form>"; 

    if(isset($_POST['add'])){
        addPlayer();
    }

addPlayer()函数看起来像

function addPlayer(){
    //PLAYER NAME
    if(empty($_POST['playerName'])){
    //Player Name is required
        echo "Player Name is required";
    }
    elseif(ctype_alpha(str_replace(' ','', $_POST['playerName'])) == FALSE){
        //Player Name can only be letters and spaces
        echo "Player Name can only contain letters and spaces";
    }
    else{
        $playerName = $_POST['playerName'];
    }


    //CHARACTER NAME
    if(empty($_POST['charName'])){
        $charName = "NULL";
    }
    elseif(ctype_alpha(str_replace(' ','', $_POST['charName'])) == FALSE){
            //Character Name can only be letters and spaces
        echo "Character Name can only contain letters and spaces";
    }
    else{
        $charName = $_POST['charName'];
    }

    //CLASS

    if(empty($_POST['class'])){
        $charClass = "NULL";
    }
    elseif(ctype_alpha(str_replace(' ','', $_POST['class'])) == FALSE){
            //Class can only be letters and spaces
        echo "Class can only contain letters and spaces";
    }
    else{
        $charClass = $_POST['class'];
    }

    //RACE

    if(empty($_POST['race'])){
        $charRace = "NULL";
    }
    if(ctype_alpha(str_replace(' ','', $_POST['race'])) == FALSE){
            //Race can only be letters and spaces
        echo "Race can only contain letters and spaces";
    }
    else{
        $charRace= $_POST['race'];
    }

    //LEVEL

    if(empty($_POST['level'])){
        $charLvl = "NULL";
    }
    if(ctype_digit($_POST['level']) == FALSE){
            //Level must be a number
        echo "Level must be a number";
    }
    else{
        $charLvl= (int)$_POST['lvl'];
    }
}

由于我不知道为什么它没有完成第二个if语句,所以我不确定如何用谷歌搜索我的答案。而且,我知道我的代码并不漂亮。放学十多年后,我正在重新学习。不幸的是,我不知道还能在哪里问这样的新手问题。

谢谢您的时间。

1 个答案:

答案 0 :(得分:0)

问题在于,仅当您提交new_player.php值时才包含showPF,但是第二种形式没有这样的字段。作为解决方案,只需为第二个表单添加一个隐藏字段:

<input type='hidden' name='showPF' value='New Player'>