PHP form processing

PHP form processing tutorial

This tutorial will build on the previous PHP form tutorial, introduce some more concepts of PHP form processing, HTML forms and form validation, and instead of saving data to a text file, we will save data to a MySQL database. This tutorial will assume that you’ve read the first tutorial and that you have a basic understanding of SQL and MySQL.

Create the form

Let’s look at the form we used for the first tutorial and make a few updates to it.

<form action="php-form-processor.php" method="post">
  Which is your favorite movie?
  <input type="text" name="formMovie" maxlength="50" value="<?=$varMovie;?>" />

  What is your name?
  <input type="text" name="formName" maxlength="50" value="<?=$varName;?>" />

  Please choose your gender?
  <select name="formGender">
     <option value="">Select...</option>
     <option value="M">Male</option>
     <option value="F">Female</option>

<input type="submit" name="formSubmit" value="Submit" />

We’re still using the post method. The action is now “php-form-processor.php”, since this is a new example, and we’ve added a new input: a “select” box, also known as a “drop-down” or “pull-down” box. A select box contains one or more “options”. Each option has a “value”, just like other inputs, and also a string of text between the option tags. This means when a user selects “Male”, the “formGender” value when accessed by PHP will be “M”.

Getting the form data in the PHP script

Let’s look at some PHP code to process this form.

if($_POST['formSubmit'] == "Submit") 
   $varMovie = $_POST['formMovie'];
   $varName = $_POST['formName'];
   $varGender = $_POST['formGender'];
   $errorMessage = "";

   // - - - snip - - - 


Select box input is accessed just like a text box. Now let’s put in some validation.

Validating the form data

It’s always a good idea to have a “blank” option as the first option in your select box. It forces the user to make a conscious selection from the box and avoids a situation where the user might skip over the box without meaning to. Of course, this requires validation.

   if(empty($varMovie)) {
      $errorMessage .= "<li>You forgot to enter a movie!</li>";
   if(empty($varName)) {
      $errorMessage .= "<li>You forgot to enter a name!</li>";
   if(empty($varGender)) {
      $errorMessage .= "<li>You forgot to select your Gender!</li>";

(For a generic, easy to use form validation script, see PHP Form Validation Script)

It’s also a good idea to put your validation checks in the same order as the inputs appear on the form. This way, if there are multiple errors, correcting them will be easier for the user. One other missing piece is that, as before, we want to preserve the user’s choice in the select box, just in case there’s a validation error in one of the other fields.

Here is how to do that:

Please choose your gender
<select name="formGender">
   <option value="">Select...</option>
   <option value="M"
 <? if($varGender=="M") echo(" selected=\"selected\"");?> >Male
   <option value="F"
 <? if($varGender=="F") echo(" selected=\"selected\"");?> >Female

This code isn’t the easiest to look at! Basically what is happening here is that for whatever option the user has already selected, we want to put a selected=“selected” property in that option box. Now the select box choice will be preserved when the form is submitted.

If this code seems ugly, don’t worry. Many select boxes will be populated from a database table, and won’t require you to write a bunch of embedded “if” statements. Also, using a select box for ‘Gender’ probably isn’t the best choice: radio buttons might make more sense

Saving the form data to a MySQL database

In the previous example, the form data was saved to a text file. This may be useful sometimes, but usually data is much more easily stored and retrieved in a database. In this example, we’ll look at inserting the data into a MySQL table.

For this example, we’re going to assume that a table called ‘movieformdata’ already exists with 3 columns: ‘moviename’, ‘yourname’, and ‘Gender’, and we’re going to assume that moviename and yourname fields can store at least 50 characters, and Gender can store at least 1 character. Hopefully you are familiar with SQL and you recognize this “insert” statement:

INSERT INTO movieformdata (moviename, yourname, Gender) VALUES ('Jaws','Bob','M');

There are 3 steps to interacting with the database in this form:

  1. Connect to the database
  2. Construct a SQL command string
  3. Execute the SQL command string

To connect to a MySQL database, PHP has some built-in functions:

   $db = mysql_connect("servername","username","password");
   if(!$db) die("Error connecting to MySQL database.");
   mysql_select_db("databasename" ,$db);

Substitute your information into these functions where necessary. “servername” is usually “localhost” or something like “”. The mysql_connect function connects to the MySQL server. If it fails to connect, the PHP script will die with an error message. Otherwise, you must then select a database on the server. Once these steps are performed, you now have a connection to a database, and can start running SQL commands on it.

Now, assuming the form is valid, let’s construct a SQL command. It’s important to talk about a security concept here: SQL Injection. This tutorial will not cover it in-depth, but if you plan to make a a public web form, you should be well-versed in SQL injections and how to prevent them. In the meantime, the example script contains a “PrepSQL” function that will “sanitize” inputs from the form. Here’s how to construct the SQL string:

$sql = "INSERT INTO movieformdata (moviename, yourname, Gender) VALUES (".
         PrepSQL($varMovie) . ", " .
         PrepSQL($varName) . ", " .
         PrepSQL($varGender) . ")";
function PrepSQL($value)
    // Stripslashes
        $value = stripslashes($value);

    // Quote
    $value = "'" . mysql_real_escape_string($value) . "'";


I usually use multiple lines when creating SQL queries, just for the sake of readability. Also notice that the PrepSQL function will add the quotes around the variable for you. Very handy, and it also improves readability.

Now that you have a SQL query constructed, run it!


In a real-life situation, you should put some error checking on this, but it will do fine for our purposes.

Download the code

Download the PHP form processing sample code here:

See Also