Tuesday, 28 August 2018

PHP Validation Form Does Not Return Correct Response

I'm new to PHP and trying to write a bit of code that validates a form on the same page before then submitting the post to a database.

What i want is for the code to;
  1. ask if any of the fields have been filled
  2. if so check if any of the fields are empty (is so output a message)
  3. if not go through a series of validation checks of the data each time adding any errors to an array.
  4. finally ask if any errors have been found
  5. if not insert the data into a database (this bit of code is written but not shown in the code i provide below.
So here is my code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>

if(isset($_POST['title']) || isset($_POST['content']) || isset($_POST['comment_option']));

{

$title = $_POST['title'];
$content = $_POST['content'];
$comment_option = $_POST['comment_option'];
$form_errors = array();

if (empty($title) || empty($content) || empty($comment_option))
{

    $form_errors[] = "All fields are required!";

} else {

    if (strlen($title < 3)){

        $form_errors[] = "The title is too short!";

    }

    if (strlen($title > 50)){

        $form_errors[] = "The title is too long!";

    }

    if (strlen($content < 50)){

        $form_errors[] = "Post is a bit short!";

    }
}

if(!empty($form_errors)) {

print_r($form_errors);

}else{

//insert data into database

}

}
?>

<form action="add_post.php" method="post">

Title: <input type="text" name="title"><br>

Content: <input type="text" name="content"><br>

Comments enabled?<br>

<input type="radio" name="comment_option" value="true">Yes<br>
<input type="radio" name="comment_option" value="false">No<br>

<input type="submit">

</form>

<body>
</body>
</html>

When i load the page i get three errors of an undefined index on the lines where i set the $title $content and $comment_option variables. If i just hit submit then i only get an error on the line where im setting the $comment_option variable but i do see "All fields are required". I also see this error if any of the fields are not filled in so this part works.
If all fields are filled in. No matter what the length i always see "Title is too short" and "Blog post is a bit short" even when they're not..
Iv spent a while looking at this and just cant figure it out what iv done wrong!
Any help would be much appreciated!!
Thanks, Max

You've put the < 3 comparison inside the function call to strlen (and the other two as well). So change from
if (strlen($title < 3)){

to
if (strlen($title) < 3){

and similarly for the other comparisons.
The undefined index errors can be fixed by changing the setting of the variables to something like this:
$title = isset($_POST['title']) ? $_POST['title'] : '';

0 comments:

Post a Comment