0

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?

2
  • Have you added any validations?? Commented Nov 28, 2014 at 6:09
  • @sgt i have added validation Commented Nov 28, 2014 at 6:21

1 Answer 1

2

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/>";
        }
    }
 ?>
Sign up to request clarification or add additional context in comments.

2 Comments

Thank You. It works. But is there a way in which it could tell which one is empty?
When i tested it without anything written, it shows an empty page. No error shown.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.