Coding - Databases - HTML - PHP

PHP Basics: Forms

Even today, in the age of apps and streaming video, HTML remains the backbone of the browsable web. But unless you want a static, brochure-type website, you’ll need at least one scripting language to add dynamic content and functionality on top of your HTML. This is the latest in a series of tutorials here on covering the basics of PHP programming. Last time, we covered connecting to and using a MySQL database. Now, it’s time to move on to perhaps the most useful function of any web scripting language: dealing with forms.

In this tutorial, I’ll walk you through how to parse form data in PHP, then two methods for using that data after it’s been collected. Before all that, though, let’s take a step back and look at the four steps that make up any useful web form.


Submit, Validate, Process, Return

Whether it’s a contact form, an order form, a suggestion box, or any other kind, every form operates in these three basic steps. First, a user fills out and submits the form. Then, some scripting language (in this case, PHP) validates the data entered, to make sure it’s been entered correctly. If it hasn’t, the user must submit it again. If the data passes the validation tests, the script then processes the data, which can include inserting it as a record into a database, completing a product order, etc. Finally, some response is returned to the user, letting them know that the process is complete. Possible returns can include order confirmations, thank you messages, or calls to action as to what the user should do next.

A Simple Form

Let’s get started with a simple form. Create a new file called form.php, and enter the following code:

<!DOCTYPE html>
    <title>PHP Basics: Forms</title>
    <form method="post" action="formresult.php">
      First Name: <input type="text" name="firstname" /><br />
      Last Name: <input type="text" name="lastname" /><br />
      Email: <input type="text" name="email" /><br />
      Comments: <textarea name="comments" > </textarea> <br />
      <input type="submit" value="Proceed!" /><br />

You’ll notice this form actually has no PHP in it. For a basic introduction, we don’t need any scripting before the submit phase of the process. Once that “Proceed!” button is pushed, that’s where the PHP comes in.

Basic Validation

The first thing that PHP can do for your form is to validate that the data submitted by the user is appropriate and usable. We’re going to start out with a very simple validation, making sure first that all three required fields (“First Name”, “Last Name”, and “Email”) have been filled in, then that the “Email” field contains an @ symbol and a dot, since no email can be valid without those two things.

Create a new PHP file, and name it formresult.php. Insert the following code:

  $firstname = $_POST['firstname'];
  $lastname = $_POST['lastname'];
  $email = $_POST['email'];
  $comments = $_POST['comments'];

  if ($firstname && $lastname && $email) {
    if ((strpos($email, '@') !== FALSE) && (strpos($email, '.') !== FALSE)) {
      echo 'VALID';
    } else {
      $error = 'The email you entered was not valid. Please try again.<br />';
      include 'form.php';
  } else {
    $error = 'Not all fields were filled out. Please try again.<br />';
    include 'form.php';

If the two conditions for validation are met – content in all three required fields and both a ‘@’ and a ‘.’ in the email field, then the data is considered valid and can move on. If not, then the user is shown the original form again, along with an error message.

In order for the error message to show up, we’ll need to add a few lines of PHP to our first file, form.php. Add this code on a new line after <body> and before <form>:

      <?php  if ($error) { echo $error; } ?>

Load form.php in your browser and try it out with both valid and invalid data to make sure that your validation filters are working correctly before we move on.

Validation is all fine and good, but processing is the real meat of any form handling PHP script. This is where you tell PHP what to do with that valuable user data you have been given. I have two different examples of processing functions for your example form. Both are pretty common uses of form data, and in fact many applications will use both at the same time.

Processing, Option 1: Email

The first thing that we can do with validated form data is incorporate it into an email. This is a common way of dealing with contact forms, but can also be useful for generating email receipts and order confirmations, and many other user experiences.

Remember that unsatisfying and unfunctional line in our formresult.php page, echo 'VALID';? Delete that line, and replace it with the following:

	$message = "First Name: ".$firstname.
		"\r\nLast Name: ".$lastname.
		"\r\nContact Email: ".$email.
		"\r\nComments: ".$comments;

	$message = wordwrap($message, 80, "\r\n");

            'New Contact Form Message from '.$firstname.' '.$lastname, 

Just replace YOUR_EMAIL with the email address where you want to receive contact form replies, and every time a valid form is filled out, you will get an email from your PHP server. If you use an email-based customer relationship manager (CRM), you can also send the email straight to that, to make sure every new contact is recorded.

Processing, Option 2: Database

If you don’t use an outside CRM, you’ll probably want to keep some record of contacts made through your website. And if you are selling a product, you will definitely need to log your orders. So let’s look next at how to enter the results of a form into your database.

We’ll start by recycling the database connection code from our PHP/MySQL Basics tutorial. Put this code in a new file, called connect.php:

    $con = new mysqli("localhost", "user", "password", "databasename");

    if($con->connect_errno > 0){
      die('Unable to connect to database [' . $con->connect_error . ']');

As always, insert your own values for host, user, password, and database name, and run the new file in your browser to check for errors before moving on.

Next, comment out the email portion of formresult.php by placing a /* comment opener before $message = and a */ comment closer after $message);. This will let us play with the database functions a little without sending any unnecessary emails.

We’ll have to set up a database table to hold our example form data. Start a new PHP file and call it create.php. Enter the following code:


    include 'connect.php';

    $createtable = 'CREATE TABLE IF NOT EXISTS contact (
        timestamp int, 
        firstname varchar (150),
	lastName varchar (150),
	email varchar (150),
	comments text

    if(!$result = $con->query($createtable)){
      die('There was an error running the query [' . $con->error . ']');


Run this file in your browser once, and your database table will be up and ready to populate with data from the example form.

Now, back to formresult.php. Just below the commented-out email section of code, inside the same set of brackets, add the following to process the form data into your new table:


    include 'connect.php';

    $timestamp = time();

    $newline = "INSERT INTO contact 
      (timestamp, firstname, lastname, email, comments) 
      VALUES ($timestamp, '$firstname', '$lastname', '$email', '$comments')";

    if(!$insertcontact = $con->query($newline)){
      die('There was an error running the query [' . $con->error . ']');


The Return

Now that you have built a form, validated its data, and processed it into either an email or a database table (or, if you remove the comment tags, both), it’s time to give the user that reassuring return message. After the code we just added to formresult.php, add the following simple return:

  echo 'Thank you for getting in touch. 
  We will get back to you as soon as possible.';

This way, the user knows that the form has gone through and that they can expect a response. There’s one more step of course, specific to contact forms: Follow up! That return message is a promise to get in touch. Don’t break it.

That pretty much covers the basics of PHP form handling. As always, play with the code yourself and add functions in to customize the form, validation, processing, and return for your own purposes. Good luck, and happy programming!

About the author

Ian Rose is a web developer, blogger, and writer living in Portland, OR. In his day job, he develops WordPress plugins and custom PHP solutions, focusing on nonprofit clients. By night, he attempts to write both fiction and nonfiction. Ian's site is Seaworthy Web Solutions

Share this post

Leave a Comment

Subscribe To Our Newsletter