I've checked it too many times but I couldn't find anything wrong with the codes but one thing that seems wired to me is that, when I disable database from the page then the form validation works fine and right after adding the database again the whole form validation collapses and the datas gets submitted without any validation.
Here's the code that I've used:
<?php
// connect to the databsae
include('config/db_connect.php');
$title = $email = $ingredients = '';
$errors = array('email' => '', 'title' => '', 'ingredients' => '');
if(isset($_POST['submit'])) {
// check email
if (empty($_POST['email'])) {
$errors['email'] = "An email is required <br />";
}else{
$email = ($_POST['email']);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'] = "email must be a valid email address";
}
}
// check title
if (empty($_POST['title'])) {
$errors['title'] = "An title is required <br />";
}else{
$title = ($_POST['title']);
if(!preg_match('/^[a-zA-Z\s]+$/', $title)){
$errors['title'] = "Title must be letter and spaces only";
}
}
// check ingredients
if(empty($_POST['ingredients'])){
$errors['ingredients'] = 'At least one ingredient is required <br />';
} else{
$ingredients = $_POST['ingredients'];
if(!preg_match('/^([a-zA-Z\s]+)(,\s*[a-zA-Z\s]*)*$/', $ingredients)){
$errors['ingredients'] = 'Ingredients must be a comma separated list';
}
}
if (array_filter($errors)){
echo "There are errors in the form";
}else{
// to make sure the data incerted inside the database is safe
$email = mysqli_real_escape_string($conn, $_POST['email']);
$title = mysqli_real_escape_string($conn, $_POST['title']);
$ingredients = mysqli_real_escape_string($conn, $_POST['ingredients']);
}
// create sql to add data to the database
$sql = "INSERT INTO pizzas(title,email,ingredients) VALUES ('$email', '$title', '$ingredients')";
// save to database and check
if (mysqli_query($conn, $sql)){
// success
header('Location: index.php');
}else{
// error
echo 'query error: ' . mysqli_error($conn);
}
}
You have not set an exit point from the script and the script continues to run, even if errors are found. You can add die
or etc. like this:
if (array_filter($errors)) {
echo "There are errors in the form";
die(1); //or exit or return if it is function
} else {
// to make sure the data incerted inside the database is safe
$email = mysqli_real_escape_string($conn, $_POST['email']);
$title = mysqli_real_escape_string($conn, $_POST['title']);
$ingredients = mysqli_real_escape_string($conn, $_POST['ingredients']);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.