Dark King
Dark King

Reputation: 71

Adding records to database with php using form

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

Answers (1)

Manish Jangir
Manish Jangir

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

Related Questions