dthtvk3666 2018-04-20 04:23
浏览 72
已采纳

如何抛出验证错误

registration_from.php

     <!DOCTYPE HTML>
        <html>
       <head>
        <title>Register</title>
       </head>
       <body>
        <form action="" method="POST">
        Name: 
        <input type="text" name="name">
        <br/> <br/>
        Username: 
        <input type="text" name="username">
        <br/> <br/>
        Password:
        <input type="password" name="password">
        <br/> <br/>

        Email: 
        <input type="text" name="email">
        <br/> <br/>
        <input type="submit" name="submit" value="Register">
    </form>
</body>
  </html>
   <?php
  require('connect.php');
  require('validation.php');
$name = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];

$email = $_POST['email'];

   if(isset($_POST["submit"])){
    if($query = mysqli_query($connect,"INSERT INTO users 
 (`id`,`name`,`username`, `password`, `email`) VALUES ('','".$name."', 
    '".$username."', '".$password."', '".$email."')")){
        echo "Success";
    }else{
        echo "Failure" . mysqli_error($connect);
      }
      }
 ?>

validation.php

     <?php
   // define variables and set to empty values
    $nameErr = $emailErr = $userErr = $passwordErr = "";
     $name =  $email = $username =$password = "";


     if (isset($_POST['submit'])) {
     if (empty($_POST["name"])) {
        $nameErr = "Name is required";
      } else {
       $name = test_input($_POST["name"]);
       // check if name only contains letters and whitespace
      if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
       $nameErr = "Only letters and white space allowed"; 
       }
       }

      if (empty($_POST["email"])) {
        $emailErr = "Email is required";
       } else {
      $email = test_input($_POST["email"]);
        // check if e-mail address is well-formed
       if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $emailErr = "Invalid email format"; 
       }
       }

        if (empty($_POST["username"])) {
      $userErr = "Username is required";
     } else {
      $username = test_input($_POST["username"]);
     }

     if (empty($_POST["password"])) {
       $passwordErr = "Password is required";
     } else {
       $password= test_input($_POST["password"]);
      }

  }

   function test_input($data) {
     $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
    }
   ?>

connect.php

  <?php
  $connect = mysqli_connect("localhost", "root", "","php_forum") 
  or die("Error " . mysqli_error($connect)); 
    ?>

I'm developing a simple Registration from with four inputs i.e., Name, username, password, email.when the user fills out the form and click submit button then all the filled data should go n save in data base which is working fine in my case, but when the user wont fill any data and if user simply clicks a submit button then error message should be shown like "ALL FIELDS ARE NECESSARY", but where in my case even if i click submit button without entering any values the mesage i'm getting as success and all the null values are getting stored in the data base which should not happen, my output should be if i fill the forms n click submit button then all the data should be stored in database and if i click submit button without filling out any value then error should throw that "all field to be filled" and no null value should be stored in data base, please can any one guide me what changes i should do so that to get my desired output.

  • 写回答

3条回答 默认 最新

  • duandong2562 2018-04-20 05:09
    关注

    If you don't mind adding a little more code, you code do like:

    In your registration_form.php

    <?php
    require('validation.php'); // Require first to do validation before queries
    require('connect.php');
    
    // Remove the part where you set variables to $_POST params
    // Variables are already set inside validation.php
    
    /**
    * Then, I recommend moving queries to **connect.php**
    * to have all your sql functions inside one file.
    * Also moving the inserting of data to a function for easy grouping/calling
    */
    
    if (isset($_POST["submit"]) {
        // Check if validation does not fail
        if ($emailErr == "" || $nameErr == "" || $userErr == "" || $passwordErr == "") {
            // Call to insert function
            doInsert($name, $email, $username, $password);
        } else {
            echo $emailErr . " " . $nameErr . " " . $userErr . " " . $passwordErr;
        }
    }
    
    ?>
    

    In your connect.php

    function doInsert($name, $email, $username, $password) {
        $connect = mysqli_connect("localhost", "root", "","php_forum")
            or die("Error " . mysqli_error($connect));
    
        $sql = "INSERT INTO users(`id`,`name`,`username`, `password`, `email`)
                VALUES ('','".$name."', '".$username."', '".$password."', '".$email."')";
    
        $query = mysqli_query($connect, $sql);
    
        if ($query) {
            echo "Success";
        } else {
            echo "Failure " . mysqli_error($connect);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输