我在尝试运行isset()函数返回true的函数时遇到问题

时间:2018-11-04 14:46:26

标签: php arrays forms function

我的if(isset($_POST['submit']))代码有点问题。我想要的是在单击表单的提交按钮后运行processForm()函数。问题在于,当我包含if(isset($_POST['submit']))函数时,当我单击提交按钮时,processFunction()根本不会运行。但是当我包含if( !isset($_POST['submit']))时,processForm()函数运行...为什么会这样,请您帮我解决这个问题

<html>
    <head>
        <title>Membership Form</title>
        <style type="text/css">
            .error { background: #d33; color: white; padding: 0.2em; }
        </style>
    </head>
<body>

    <?php 
        if ( isset($_POST["submit"])) { //if submit input has value
                        processForm();//calls the processForm function
                    }

        function processForm(){ 

            $compulsaryForm = array("firstName" , "lastName", "password" , "passwordRetype");
            $missingFields = array();

            foreach ($compulsaryForm as $input) { //loop
                if (!isset($_POST[$input])) {
                    $missingFields[] = $input;
                } // forget the else part cause we mainly want to avoid the warning msg
            }

            if ($missingFields) {
                echo "<p>there are missingFields</p>";
            }

        }

     ?>

<form action="htmlForms2.php" method="post">

    *name:<input type="text" name="firstName"> <br><br>
    *last name: <input type="text" name="lastName"> <br><br>
    *password<input type="password" name="password"> <br><br>
    *retype password<input type="password" name="passwordRetype"><br><br>

    male:<input type="radio" name="sex"><br>
    female:<input type="radio" name="sex"><br>

    favourite food:<select name = "favourite">
                        <option value="select">select</option>
                        <option value="rice">rice</option>
                        <option value="beans">beans</option>
                    </select><br>

    do you want to recieve news letter?<input type="checkbox" name="newsLetter"><br>

    Any comments? :<input type="text" name="comments"><br>

    <input type="reset" name="reset">
    <input type="submit" name="submit" value="submit">

</form>

1 个答案:

答案 0 :(得分:0)

您的代码在“提交”字段验证方面看起来不错。这些行看起来不太好:

$compulsaryForm = array("firstName" , "lastName", "password" , "passwordRetype");
$missingFields = array();

foreach ($compulsaryForm as $input) { //loop
  if (!isset($_POST[$input])) {
    ...

您要验证的所有输入都将在提交中发送,因此isset(...)将是true,它们可能为空,但可以肯定地存在。因此,请在服务器端或在发送表单之前验证您的空缺,或者在两个地方都更好,这应该可以工作;)

// Use: count($_POST[$input]) < 5, In case you want to validate the text length 
if ( !isset($_POST[$input]) || empty($_POST[$input]) || count($_POST[$input]) < 5 {