请任何人可以帮助我指出此代码中的错误吗?.php新手
  表单成功提交到数据库并同时显示
  验证错误,如果它要求在提交之前通过验证
  到mysql db。例如,当一个字段为空时,它将显示
  错误消息,指出该字段为空并同时插入
   进入数据库。

    <?php
    require_once("validation_function.php");

    $errors=array();
    $message = "";
    $username= "";
    $password= "";

    if(isset($_POST["submit"])){

     // open a connection to the database
     include("db_connect.php");
     // initialize variables with form data.

     $username =trim($_POST["username"]);
     $password =trim($_POST["password"]);
      //validations


      $field_required= array("username", "password");
        foreach($field_required as $field){
        $value= trim($_POST[$field]);
          if(!has_presence($value)){
           $errors[$field]= ucfirst($field) . " can not be blank";
           }
       }

        $field_required_max = array("username"=>30,"password"=>8);
        foreach($field_required_max as $field=> $max){
          $value=trim($_POST[$field]);
             if(!has_max_lenght($value,$max)){
            $errors[$field]= ucfirst($field) . " is too long";
            }

         }


       $query = "INSERT INTO test (";
       $query .= " username, password";
       $query .= ") VALUES (";
       $query .= " '{$username}', '{$password}' ";
       $query .= ")";
       $result= mysqli_query($connection, $query);

      if($result==1){
          echo "records inserted successfully";
       }else{
         die("data base query failed " . mysqli_error($connection));
        }

          if(isset($connection)){ mysqli_close($connection); }

    }
       ?>

     <html lang="en">
       <head>
         <title>single page form with validations</title>
     </head>
      <body>
       <?php echo form_errors($errors);?>
          <form action="form_with_validation.php" method="post">
            <p>username <input type="text" name="username" value ="" />
           </p>
         <p>password <input type="password" name="password" value=""></p>
       <input type="submit" name="submit" value="submit"/>
      </form>
     </body>
    </html>

最佳答案

您将错误存储在$ errors变量中,但是尚未检查是否存在错误。

在插入数据库之前,您需要检查是否有任何错误。

.... Other code ....
foreach($field_required_max as $field=> $max){
    /* Statements */
}

/* $errors contains the error messages */
/* Insert into database if no errors are present */

if (!$errors) {

    $query = "INSERT INTO test (";
    .....
    $result= mysqli_query($connection, $query);

    if ($result==1) {
        echo "records inserted successfully";
    } else {
         die("data base query failed " . mysqli_error($connection));
    }
}

关于php - 即使字段为空白,此php表单也通过验证,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39319576/

10-13 04:26
查看更多