Reputation: 71
I have made a form in which i am able to enter records into the database. But the form enters the records even if i enter nothing in them and hit 'Submit'.
Here is my code:
$sql = "INSERT INTO blog_posts (title, body) VALUES ('$post_title', '$post_body')";
if(mysqli_query($link, $sql)){
echo '<p class="sucessful">Post Added Successfully.</p>';
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
So is it possible to make it require to fill in the forms before submitting? or show an error if submitted when the form is not filled?
Upvotes: 0
Views: 47
Reputation: 5437
You can use
<?php
$errors = array();
if(empty($post_title)) {
$errors[] = "Post Title is empty";
} else if(empty($post_body)) {
$errors[] = "Post Body is empty";
}
if(!empty($errors)) {
$sql = "INSERT INTO blog_posts (title, body) VALUES ('$post_title', '$post_body')";
if(mysqli_query($link, $sql)){
$errors[] = '<p class="sucessful">Post Added Successfully.</p>';
} else{
$errors[] = "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
if(!empty($mysqlErrors)) {
foreach($mysqlErrors as $error) {
echo $error."<br/>";
}
}
} else {
foreach($errors as $error) {
echo $error."<br/>";
}
}
?>
Upvotes: 2