Got two questions about my validation form

First most importantly how do i submit the validated form to go to thankyou.php (Enters the data into the database) as my form action/target is index.php. Second can i put multiple variables into an if statement. For example IF(empty($name $email)){}

Here’s my code:

<?php
error_reporting(E_ALL);

$name_error = null;
$email_error = null;
$subj_error = null;
$message_error = null;

if(isset($_POST['submit'])){
        $name = $_POST['u_name'];
        $email = $_POST['u_email'];
        $subject = $_POST['subj'];
        $message1 = $_POST['message'];

        if(empty($name)){
        $name_error = "Please enter your name";
        }
        if( !preg_match ("/^[a-zA-Z\s]+$/",$name)) {
        $name_error = "Name must only contain letters!";
        }
        if(strlen($name) <= 2){
        $name_error = "Name must contain atleast 3 letters";
        }
        if(strlen($name) >= 30){
        $name_error = "Name must contain less than 30 letters";
        }
        if(empty($email)){
        $email_error = "Please enter your email";
        }
        if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $email_error = "Invalid email format";
        }
        if(empty($subject)){
        $subj_error = "Please enter your subject";
        }
        if( !preg_match ("/^[a-zA-Z\s]+$/",$subject)) {
        $subj_error = "Subject must only contain letters!";
        }
        if(strlen($subject) <= 2){
        $subj_error = "Subject must contain atleast 3 letters";
        }
        if(strlen($subject) >= 30){
        $subj_error = "Subject must contain less than 30 letters";
        }
        if(empty($message1)){
        $message_error = "Please enter your message";
        }
        if( !preg_match ("/[A-Za-z0-9]+/",$message1)){
        $message_error = "Your message must not contain special characters";
        }
        if(strlen($message1) <= 5){
        $message_error = "Message must contain atleast 5 letters";
        }

}
?>


by submit i think you mean re-direct? If you mean re-direct you can use the php header() function to re-direct you.

header("location:/thankyou.php");

If you mean a form submit you would add that to the html form’s action attribute. Or use ajax.

You cannot as far as i know do empty($var, $var2)
But you can do this which is the way to do it.

if(empty($var1) and empty($var2))
{
        //do something
}

or

if(empty($var1) or empty($var2))
{
        //do something
} 

if(($name ==“”) || ($email==“”)) or if ( (empty($name) ) || (empty($email) ) )

You can include thankyou.php in index.php

or you can redirect

header(“Location: thankyou.php?name_error=”.$name_error.“&email_error=”.$email_error.“&subj_error=”. $subj_error.“&message_error=”.$message_error);

That is what I was showing you here.

Separating your php processing from your html, will not only make cleaner, less complex documents, but will offer greater flexibility.

If i use header(“location:/thankyou.php”); would i be able to re-direct the original $_POST variables if all the errors are null?

The header redirect would forward you to another php script, so the post data will be lost along with the other variables defined in the processing script.
Using the method (as above) of including different html templates according to the form results will allow you to access any post data or variables within the processing script.

Could you make an example based on my code of what you are explaining?

I don’t have the time right now, but there is my “bare-bones” example in the post I linked above which is a start.
The principle is 3 different files, the php controller script and 2 html pages (the form and the thank you pages) which may get included based on conditions of the form results.
Theoretically there could be any number of different html pages output by the one script using this method.

That has confused me.

I’m referring to my example code in this post.
It is not a working example, but stripped down to the bare logic of this method to make it clearer.
It is well commented to explain things.

Found that confusing as well.

If you explain exactly what you found confusing, someone might be able to explain it to you.

Everything SamA74 said.

The example is a nested conditional structure.

There are two possible “submitted” states.
Either the form was submitted or it was not.
If the form was submitted there are two possible “quality” states.
Either there was an error(s) or there was no error.

Looking at the indentation is a big help at making the distinction more easily recognizable as to which section belongs to which conditional test.

3 Likes

+1 for indentation. I believe before learning any actual programming language, schools and tutorials online should teach the basics. The very first basic before logic should always be indentations. I cannot stress this enough.

It makes it very hard for others if things aren’t formatted correctly.

3 Likes

We could go through it one step at a time in a hypothetical scenario where a visitor goes to your form page and fills it in.
For reference, here it is again in one place.

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") { // The form is submitted
    
    // do the validation here
    
    // Then, depending on how that turns out...
    if(isset($errors)) {   // There are errors in the submission
        
        // Show the user the form again, with errors listed
        include 'html_form_template.php' ;
    }
    
    else {  // Everything is cool with the form submission
        
        // Send the email
        // Record to database
        
        // Show the user Thank You message
        include 'html_thankyou_template.php' ;
    }
}   // end the form is submitted

else {  // Nothing has been submitted
    
    // Show the user the form for the first time
    include 'html_form_template.php' ;
}

?>

First of all a visitor lands on your form for the first time. The php script starts to process.
The very first thing is this if condition.

if ($_SERVER["REQUEST_METHOD"] == "POST") { // The form is submitted
}

This tests whether the request method is post (or not). As in: Has a form been submitted where the form method is “post”?
Because the visitor has only just reached the page for the first time and has not filled anything in, the test returns false and the processing skips whatever is between those brackets.
But the closing bracket of the if is immediately followed by an else.

else {  // Nothing has been submitted
    
    // Show the user the form for the first time
    include 'html_form_template.php' ;
}

So the script does whatever is in those brackets.
There we have a php include.

The include statement includes and evaluates the specified file.

The included file could be whatever you like, but in this case it would be an html document which contains your html form.
Therefore, that is what your visitor will see, on this occasion, your html form.

Next, the visitor fills in the form and hits the submit button.
Because the form element’s action attribute contains reference to this self same script, the script loads again and is evaluated again from the top.

Again, we start with the if condition:-

if ($_SERVER["REQUEST_METHOD"] == "POST") { // The form is submitted
}

Only this time around, the form has been submitted and the method was post, so the if condition returns true.
So the script does what is in this first pair of brackets, not the second else pair.
The next thing we see is:-

// do the validation here

OK, that’s just a comment as a placeholder for the actual validation code which would be there.
I did not want to spend my time complicate things further by putting all that in there.
But just a little now to demonstrate.

if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
      $email = $_POST['email'];
}
else {
      $errors[] = "You did not supply a valid email address!" ;
}

This if condition uses a validation filter to check if the input string looks like a valid email address. It saves you having to do some complex regex to find this out.
Supposing that the visitor makes a mistake and misses out the @ or something, that won’t validate so the condition will return false, the first brackets get skipped and you move on the the else where we find:-

$errors[] = "You did not supply a valid email address!" ;

This adds a string (error message) to an array named $errors.

Note: This is not how error messaging/handling is done in some other examples. This is just how I do it. I’m not saying this is the only way or best way, just my way.

That other example you had defines a bunch of variables for various errors as empty strings at the beginning, then fill them in if the errors occur.
I am adding each error that occurs to an array. The array is not predefined, so will not exist unless one or more errors occur during validation.
That comes in useful for the next if condition.

There will be more validation for the rest of the form fields which will return true or false and may or may not append the $errors array with more messages. But one example of that is enough.
So on to the next if condition.

if(isset($errors)) {   // There are errors in the submission
}

This will return true only if $errors is set.
Because the visitor got the email address wrong, there is an entry in the $errors array, so it is set, it returns true.
And in those brackets we see:-

        // Show the user the form again, with errors listed
        include 'html_form_template.php' ;

That same php include again which displays to them the html form so they get another go at filling it in properly.
Because there exists an array containing any/all validation errors, they can be echoed out via a foreach in the form page.
Note: That will involve ‘tainting’ your html with a bit of php, but ho-hum, it’s going to happen a bit at some point, just try keep it to a minimum.

The visitor now sees the form again, with a list of errors telling them what they did wrong, so they can correct and resubmit.
And the script starts over again.

if ($_SERVER["REQUEST_METHOD"] == "POST") { // The form is submitted
}

This is true again. But this time all validation gets passed. Nothing gets added to the $errors array, in fact, the $errors array never gets defined, it does not exist this time.
As a result…

if(isset($errors)) {   // There are errors in the submission
}

…returns false, so those brackets get skipped and you move on to the else.

    else {  // Everything is cool with the form submission
        
        // Send the email
        // Record to database
        
        // Show the user Thank You message
        include 'html_thankyou_template.php' ;
    }

First we have this:-

        // Send the email
        // Record to database

Again, just comments as placeholders for the actual code that will perform these actions, quite self explanatory. No need to go into that just now.
Followed by another php include:-

include 'html_thankyou_template.php' ;

But this time to a totally different html document. Not the form, but the “Thank you” page.
Because we are still in the processing script, not redirected to another page (though displaying to the visitor a separate external document file) all the post data and stuff parsed from the form is still available, so could be echoed out in the html page if required.
The form process is now complete.

If that does not explain it, I don’t know what to suggest. A good book or php course perhaps.

6 Likes

I’m not sure what to put in the if statemant isset($errors)
This is what i have so far:

<?php
error_reporting(E_ALL);

if ($_SERVER["REQUEST_METHOD"] == "POST") { // The form is submitted

    // do the validation here
        if(empty($u_name) or empty($u_email) or empty($subj) or empty($message)){
        $empty_error = "Please fill the empty form";
}
        if(!preg_match ("/^[a-zA-Z\s]+$/",$u_name) or !preg_match ("/^[a-zA-Z\s]+$/",$subj) or !pregmatch ("/^[a-zA-Z0-9]+/",$message))
        $preg_match_error = "Invalid syntax";
}
        if(strlen($u_name) <= 2 or strlen($u_email) <= 2 or strlen($subj) <= 2 or strlen($message)<= 2){
        $strlen_error = "Must contain more than 2 letters";
}
        if(strlen($u_name) >= 50 or strlen($u_email) >= 30 or strlen($subj) >= 20 or  strlen($message) >= 100){
        $strlen_error = "Maximum input length exceeded";
}
        if(!filter_var($u_email, FILTER_VALIDATE_EMAIL)) {
        $email_error = "Invalid email format";
}
    // Then, depending on how that turns out...
    if(isset($errors)) {   // There are errors in the submission

        // Show the user the form again, with errors listed
        include 'index.php' ;
    }

    else {  // Everything is cool with the form submission

        // Send the email
        // Record to database

        // Show the user Thank You message
        include 'thankyou.php' ;
    }
}   // end the form is submitted

else {  // Nothing has been submitted

    // Show the user the form for the first time
    include 'index.php' ;
}
?>

Just the include for the form needs to go there.

include_once $_SERVER["DOCUMENT_ROOT"] . "/includes/form.php";

This is an example, you will need to insert the path and file name for your form document.
In this example it is a file called form.php in a folder named includes.

Where you place the file and what you name it is up to you, though it’s a good idea to keep any includes that don’t work as a standalone page in a place your visitors won’t/can’t go.

As you have it $errors will never return true because it never gets defined.
You may either do it my way and put each error message into an array.

But if you prefer to fill the empty variables with error messages, then first define the empty variables, as before. But you will then need to somehow create the $errors variable for it to return true. That could be done by accompanying each error message with another line: $errors = true;

That means do either of these for each error:-

{ 
     $errors[] = "Please fill the empty form"; // create or append the $errors array
}

Or alternatively:

{
      $empty_error = "Please fill the empty form";   // Fill the empty variable
      $errors = true;    // Set $errors to true to it is set
}

Also, you don’t appear to be getting the $_POST data at all. You are validating undefined variables.

You’ve just confused me even more, do you have any code you can link me?

Why can’t i put the validation in thankyou.php, that is where the data is being recorded to the database. Surely i can put the validation in before it is recorded and if the validation fails then it stops it being recorded.