简体   繁体   English

如何抛出验证错误

[英]how to throw validation error

registration_from.php 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 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 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 ie, 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. 我正在使用四个输入来开发一个简单的注册,即名称,用户名,密码,电子邮件。当用户填写表格并单击提交按钮时,所有填写的数据都应保存在数据库中,这在我的数据库中可以正常工作情况下,但是当用户不会填写任何数据并且如果用户只是单击提交按钮时,错误消息应该显示为“所有字段都是必需的”,但是在我的情况下,即使我单击提交按钮而未输入任何值,消息我越来越成功,所有空值都将存储在数据库中,这是不应该发生的,我的输出应该是:如果我填写表格n单击提交按钮,那么所有数据都应该存储在数据库中,如果我单击提交按钮如果不填写任何值,则错误应抛出“要填写的所有字段”,并且数据库中不应存储任何空值,请任何人都可以指导我应进行哪些更改,以便获得所需的输出。

 <?php // define variables and set to empty values $name = $email = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = test_input($_POST["name"]); $email = test_input($_POST["email"]); $website = test_input($_POST["website"]); $comment = test_input($_POST["comment"]); $gender = test_input($_POST["gender"]); } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <h2>PHP Form Validation Example</h2> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> Name: <input type="text" name="name"> <br><br> E-mail: <input type="text" name="email"> <br><br> Website: <input type="text" name="website"> <br><br> Comment: <textarea name="comment" rows="5" cols="40"></textarea> <br><br> Gender: <input type="radio" name="gender" value="female">Female <input type="radio" name="gender" value="male">Male <input type="radio" name="gender" value="other">Other <br><br> <input type="submit" name="submit" value="Submit"> </form> <?php echo "<h2>Your Input:</h2>"; echo $name; echo "<br>"; echo $email; echo "<br>"; echo $website; echo "<br>"; echo $comment; echo "<br>"; echo $gender; ?> 

Please add error in session and print session in form file. 请在会话中添加错误,并在表单文件中打印会话。

In validation.php 在validation.php中

$nameErr = $emailErr = $userErr = $passwordErr = "";
$name =  $email = $username =$password = "";
if (isset($_POST['submit'])) {

 $name = $_POST["name"];
 $email = $_POST["email"];
 $username = $_POST["username"];
 $password = $_POST["password"];

if($name == '' ||  $email == '' || $username == '' || $password == "") 
 {
  echo "ALL FIELDS ARE NECESSARY";
  exit();
 }

     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"]);
      }

  }

registration_from.php registration_from.php

if(isset($_SESSION['error]) && !empty($_SESSION['error])){
   echo $_SESSION["error"]
 }

If you don't mind adding a little more code, you code do like: 如果您不介意添加更多代码,则代码会像这样:

In your registration_form.php 在您的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 在您的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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM