How to Process Form Data in PHP

In this previous lesson we styled a basic HTML form using Bootstrap.

We will now look at how we process the data from the form.

We finished the previous lesson with this HTML code:

STEP 1

The first thing we need to do is provide an action and a method for our form. 

Line 8: we are sending the form to a processing script called 'processForm.php' with a 'post' method.

STEP 2

Now let us take a look at the processing script.

First of all, we do not want this script to run unless data has been posted to the form.

There are other functions we could use such as isset().

The exclamation mark means NOT. So, line 3 literally means: if the post is not empty.

STEP 3

Next, if the 3 fields were required, we can check if each of the 3 inputs contain data.

Again, there are other ways we could handle this data. It is up to the developer to select an appropriate method and ensure that data validation is carried out.

For example, we could have taken each of the data values in turn and built up an error message e.g. The 'name' field is required.

STEP 4

So far we know that we have values in each of the 3 fields.

We can now assign the values to variables:

WARNING: we have NOT added any data validation or sanitization and we are accepting raw data from the user up to this point. Not a good idea! It is up to the developer to validate and sanitize the user input. This may vary depending on required usage. For example, some developers use comprehensive REGEX checks while others prefer the PHP functions such as filter_var. You will probably need to consider trimming white space too.

STEP 5

We can now perform some actions on the data such as inserting into a database.