dongwo5589 2016-03-25 12:01
浏览 35

PHP数据库验证

<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Book A Table</title>
</head>
<body>

<h1>Book A Table</h1>



<?php
// define variables and set to empty values
$nameErr = $emailErr = $numErr=$dateErr = $timeErr = $personsErr="";
$name = $email = $num= $date = $time = $persons = $comment= "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   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"]);
     if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format"; 
    }
   }
   if (empty($_POST["num"])) {
     $numErr = "Number is required";
   } else {
     $num = test_input($_POST["num"]);
     if (!preg_match("([0-9])", $num)) {
      $numErr = "Enter numbers only"; 
    }
   }



   if (empty($_POST["date"])) {
     $dateErr = "Date is required";
   } else {
     $date = test_input($_POST["date"]);
   }



   if (empty($_POST["time"])) {
     $timeErr = "Time is required";
   } else {
     $time = test_input($_POST["time"]);
   }
   if (empty($_POST["persons"])) {
     $personsErr = "Number of persons is required";
   } else {
     $persons = test_input($_POST["persons"]);
   }
}

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

    <form action="DBInput.php" method="POST"  />

    <p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
   Full Name<br> <input type="text" name="name">
   <span class="error">* <?php echo $nameErr;?></span>
   <br><br>
   E-mail<br> <input type="text" name="email">
   <span class="error">* <?php echo $emailErr;?></span>
   <br><br>
   Contact Number<br> <input type="text" name="num">
   <span class="error">*<?php echo $numErr;?></span>
   <br><br>
   Reservation Date<br> <input type="date" name="date">
   <span class="error">*<?php echo $dateErr;?></span>
   <br><br>
Reservation Time<br>(Mon - Thur: 18:00 - 23:00 Fri - Sun: 12:00 - 00:00)<br> <input type="time" name="time">
<span class="error">*<?php echo $timeErr;?></span>
   <br><br>
Number of Persons<br> <input type="text" name="persons">
<span class="error">*<?php echo $personsErr;?></span>
   <br><br>
Comments<br><textarea name="comment" rows="5" cols="40"></textarea><br><br>

   <input type="submit" name="submit" value="Submit"> 
</form>





</body>
</html>

What I am doing in the above code is creating a form and inputting it into a database. This is working perfectly. However I would like to add validation so that if the user does not enter all the required fields, it wont be stored in the database.

I have only started PHP this week and so im a begginner. Any idea how to do this ?

  • 写回答

2条回答 默认 最新

  • doujing5846 2016-03-25 12:46
    关注

    I can offer you something different:

    Create a file that keeps an array with validation rules of all the fields you have in your database, table by table:

    fields.php

    return [
        'users' => [ // Let's say your table is called `users`
            'name' => [
                 'required', // This means the field is required
             ],
             'email' => [
                 'email' // email validator
             ]
            // etc...
        ]
        // etc...
    ];
    

    Then create another file with validator functions:

    validator.php

    function requireValidator($value) {
        if (empty($value)) {
            return 'Required value'
        }
        return true;
    }
    
    function emailValidator($value) {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return 'This is not a valid email';
        }
    
        return true;
    }
    
    function numberValidator() and so on
    ...
    
    function validate($fields, $input) { // And here is where the validation happens
        $errors = [];
        foreach ($userInputArray as $inputField => $inputValue) {
            foreach ($userInputField as $rule) {
                 $validator = "{$rule}Validator";
                 $result = $validator($inputValue);
                 if ($result !== true) {
                      $errors[$inputField][] = $result;
                 }
            }
        }
    
        return $errors;
    }
    

    And then in your code:

    require('validator.php');
    $fields = require('fields.php');
    
    $userInput = $_POST;
    
    $errors = validate($fields['users'], $userInput);
    if (!empty($errors)) {
        // Show errors to the user
    }
    

    Basically, what I am trying to show you is that you can create validation rules at one centrelized place, and validators at another centrelized place. That way if you need to make a change, you do it at one place. What I do in the validator() function is:

    • take the rules and the user input
    • traverse through all validation rules
    • build each validation function by concatenating the name of the rule and the word 'Validator' (I put the word 'Validator' in order to mark the function as validator and make it unique. This is like convention).
    • Call each validator $validator()
    • And then take the error message if there is one.

    This is some basis which you can step on. You can create more validators and rules and make it more sophisticated.

    If you don't understand anything, please ask. You are doing a really good job, because for one week of PHP you know pretty much.

    Good luck!

    评论

报告相同问题?