<!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>
我在上面的代码中正在做的是创建一个表单并将其输入到数据库中。这很完美。但是,我想添加验证,以便如果用户没有输入所有必填字段,它将不会存储在数据库中。
本周我只启动了PHP,所以我是一个初学者。知道怎么做吗?
答案 0 :(得分:1)
我可以为你提供不同的东西:
创建一个文件,保存一个数组,其中包含数据库中所有字段的验证规则,逐个表:
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...
];
然后使用验证器函数创建另一个文件:
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;
}
然后在你的代码中:
require('validator.php');
$fields = require('fields.php');
$userInput = $_POST;
$errors = validate($fields['users'], $userInput);
if (!empty($errors)) {
// Show errors to the user
}
基本上,我要向您展示的是,您可以在一个中心位置创建验证规则,并在另一个中心位置创建验证器。这样,如果您需要进行更改,可以在一个地方进行更改。 我在validator()函数中做的是:
这是您可以踩的一些基础。您可以创建更多验证器和规则,使其更复杂。
如果您不了解任何内容,请询问。你做得非常好,因为你知道一个星期的PHP,你知道的很多。
祝你好运!答案 1 :(得分:0)
我希望这会有所帮助,我只为这个名字做了这个,但你可以添加更多来满足你的需求。
// Array to store any input validation errors
$errorArray = [];
$nameErr = "Name is required";
// test to see if the $_POST variable is set
if(isset($_POST['submit'])) {
// test to see if the $_POST variable contains the key name
if(isset($_POST['name'])) {
if($_POST['name'] == "") {
// error message for name is required.
$errorArray[] = $nameErr;
} else {
// there is a value for name do your regex here
}
}
}
// Use print_r function to see if there are any items in the errorArray for yourself
// print_r($errorArray);
// * count the values in the errorArray... this is where it will ensure that if there are any errors found it will not set the $name variable and will not call you other database functions.
if(count($errorArray > 0)) {
// loop through the errorArray and display the errors you can customize this as you see fit.
for($i = 0; $i < count($errorArray); $i++) {
echo $errorArray[$i];
}
} else {
// Your form has been submitted.
// no errors you can do database calls here.
$name = test_input($_POST['name']);
//<form action="DBInput.php" method="POST" />
// try not using the form action DBInput and make a function call instead passing in each value you need.
doDataBaseStuff($name);
}
然后你的功能......
function doDataBaseStuff($name) {
// do database stuff....
}