Fundamental forms

One of the most important uses of PHP is processing form data. This chapter shows you how to do it.

The next three chapters are about forms. This chapter starts off looking at the HTML for forms. Then it shows you how to do simple things with form data in PHP.

The next chapter looks at a couple of ways of saving form data: sending it by email, and saving it to a file.

The final form chapter talks about validation, that is, how you check data that users put into forms. We also look at how to make forms look good.

Forms in HTML

Where are we?

Let’s start by reviewing HTML form tags.

This lesson’s goals

By the end of this lesson, you should:

  • Know how browsers send form data to Web servers.
  • Know the difference between get and post.
  • Know what URL encoding does.
  • Know the basic attributes of the <form>, <input>, and <button> tags.

Form data flow

Remember HTTP? That’s the protocol that Web browsers and servers use to talk to each other.

There are various types of HTTP messages that browsers and servers send to each other. A common one is GET. This is usually how a browser asks a server for a page.

For example, suppose a user is looking at this page at http://dogsite.com/articles/index.php:

Articles list

Figure 1. Articles list

Here’s part of the HTML for the page:

<h1>Articles</h1>
<ul>
  <li><a href="why-dogs-are-great.php">Why dogs are great</a></li>
  <li><a href="playing-with-dogs.php">Playing with dogs</a></li>
</ul>

Figure 2. HTML for articles list

The user clicks the link “Playing with dogs.” The browser contacts the server at dogsite.com, and sends:

GET /articles/playing-with-dogs.php HTTP/1.1

The server sends back the HTML for playing-with-dogs.php to the browser.

When the browser sends a message like GET to the server, the browser sends other data as well, besides the URL. For example, it tells the server what type of browser it is.

GET /articles/playing-with-dogs.php HTTP/1.1
Host: dogsite.com
User-Agent: Mozilla/5.0

Host and User-Agent are headers. Each one is on a different line.

There are many header types besides Host and User-Agent. They specify the date and time the request was sent, languages the browser would prefer, and other stuff. A typical GET might have a half dozen headers.

Here’s the important bit for this chapter: the total HTTP request – the URL and the headers – can include data the user typed into form fields. This gives a way for browsers to send data to servers (usually it’s the other way around).

When the user submits a form in a Web browser, the form data travels along with a URL.

Form data attached to URL

Figure 3. Form data attached to URL

So, the form data is sent along with a URL. But which URL? What page does the browser send the data to?

The browser sends form data to a page that is specially written to handle form data. The page knows how to extract the data, and do something with it, like save it to a database. That’s one of the things you do in PHP: write pages that can handle form data.

More on that later. Right now, we’re just looking at the form.

A form example

Let’s create a form like this:

Simple form

Figure 4. Simple form

There are two text fields, and a button. Clicking the button submits the form. This means that the browser sends the form’s data to the server.

Here’s the HTML:

<h1>Simple Form</h1>
<form action="process-simple-form-get.php" method="get">
  <p>First name:
    <input name="first_name" type="text" size="20">
  </p>
  <p>Surname:
    <input name="surname" type="text" size="20">
  </p>
  <p>
    <button type="submit">Save</button>
  </p>
</form>

Figure 5. Simple form HTML

The form is wrapped in a <form> tag. This one has two attributes: action and method. There are other attributes we could use, but we don’t care about them yet.

The action says where the data should be sent. Remember that form data gets attached to a URL. This is the URL the data gets attached to.

The method attribute says how the form data will be attached. There are two ways: get and post.

The get method

get tacks the form data on to the URL itself. Suppose the user filled in the form like this:

Simple form with data

Figure 6. Simple form with data

The browser would create this URL:

/process-simple-form.php?first_name=Buffy&surname=Summers

Why this URL? Let’s look at the HTML again.

<h1>Simple Form</h1>
<form action="process-simple-form-get.php" method="get">
  <p>First name:
    <input name="first_name" type="text" size="20">
  </p>
  <p>Surname:
    <input name="surname" type="text" size="20">
  </p>
  <p>
    <button type="submit">Save</button>
  </p>
</form>

Figure 5 (again). Simple form HTML

The main part of the URL is in the form’s action property: process-simple-form.php. The browser adds a ? on the end, to indicate the start of the form data.

Then it adds the data in form fields. There’s the name of a field, an equals sign (=), and the field data. An ampersand (&) separates the fields.

So we end up with:

Get action

Figure 7. Get action

Try it. Notice that you can see the data in the address field of your browser.

Address bar for get

Figure 8. Address bar for get

The post action

Instead of the get action:

<form action=... method="get">

you can use post:

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

It works almost the same as get, except that the form data is passed through in an HTTP header, rather than concatenated to the URL. So the message from the browser to the server might look like this:

POST /articles/playing-with-dogs.php HTTP/1.1
Host: dogsite.com
User-Agent: Mozilla/5.0
Content-Length: 32
Content-Type: application/x-www-form-urlencoded

first_name=Buffy&surname=Summers

Figure 9. post message example

The form data itself has the same pattern; field name then value, field name then value, etc.

The advantage of the post method is that the data doesn’t show up in the browser’s address bar:

Address bar for post

Figure 10. Address bar for post

Only the URL shows. Headers do not.

You can try it. You won’t see the form data in the address bar of your browser.

Most Webers use method="post" because the form data doesn’t show up in the browser’s address bar. It’s a little more secure, and less annoying.

Exercise: Address form

Create a form like this:

Address form

Figure 1. Address form

Use the get method. Set the action to the page itself. For example, if you called the file ralph-the-wonder-form.html, use action="ralph-the-wonder-form.html".

When the form is filled in, it should look something like this:

Address form with data

Figure 2. Address form with data

Have a look at how the browser attaches data to the URL.

You can see my solution, but try it yourself first.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

URL encoding and character sets

Let’s do an experiment. Open the get version of the form. Try typing some special characters into the form. A special character is anything that is not a letter or a digit. For example:

Special characters in a form

Figure 11. Special characters in a form

Click the button, and look at the URL on the form processing page. You’ll see something like this:

process-simple-form-get.php?first_name=Renata+is+cute!&surname=Yes%2C+I+agree.

Some of the characters have been changed. The spaces became plus signs (+). The comma (,) became %2C.

This is called “URL encoding.” Browsers automatically URL encode data before sending it in a get or a post.

Why do browsers do this? URLs use a small character set. A “character set” is a limited group of characters to choose from. For example, when computers were first developed, most used the old US-ASCII character set. It has just the letters A to Z, the digits, punctuation(,.!; etc.) and a few other things. If you wanted to send characters with accents (like é) or currency symbols (like ¥), you were out of luck.

Other character sets were developed. Perhaps the most common international character set these days is UTF-8. It can represent thousands of characters; Cyrillic, Kanji, you name it, it’s probably in UTF-8.

The trouble is, URLs still use US-ASCII. It’s efficient, and is universally supported. So how do you send special characters in a URL?

The answer: URL encoding. It converts some special characters to a code. For example, it changes commas (,) into %2C. It also changes spaces into plus signs.

Browsers are not consistent in their URL encoding. Here’s how different browsers encode the data in Figure 11:

Firefox
first_name=Renata+is+cute!&surname=Yes%2C+I+agree.

Internet Explorer
first_name=Renata+is+cute%21&surname=Yes%2C+I+agree.

Chrome
first_name=Renata+is+cute!&surname=Yes,+I+agree.

Safari
first_name=Renata+is+cute%21&surname=Yes%2C+I+agree.

Only IE and Safari are the same.

Usually, you won’t need to worry about URL encoding. It happens automatically. But sometimes you’ll need to do it yourself in PHP. More on that later.

Exercise: Special characters in the address form

Open the page you created for the address form exercise. Type special characters into the fields. See how they are encoded in the URL generated by the form.

Make some notes below on how different characters (like %, $, +, and #) are encoded.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Text input fields

Let’s go back and look at the HTML for the text input fields.

<h1>Simple Form</h1>
<form action="process-simple-form-get.php" method="get">
  <p>First name:
    <input name="first_name" type="text" size="20">
  </p>
  <p>Surname:
    <input name="surname" type="text" size="20">
  </p>
  <p>
    <button type="submit">Save</button>
  </p>
</form>

Figure 5 (again). Simple form HTML

Line 4 sets up the first name field. <input> says it’s an input field. There are several types of input fields. Let’s stick with type="text" for now.

size sets the width of the field in number of characters. It does not limit the number of characters the user can type; size just affects the width of the field on the screen.

name is an important one. It’s the name given to the value when the data is sent to the server. You can see it in action on the last line of Figure 9.

The button

Nothing happens until the user hits the button. The HTML for our button is:

<button type="submit">Save</button>

Notice the type attribute. Earlier, we’ve seen this as type="button". When type="submit", the browser sends form data to the server when the button is pressed.

Summary

In this lesson, you learned:

  • Browsers send form data to Web servers along with URLs.
  • get attaches form data to a URL. post puts it in a separate HTTP header.
  • URL encoding handles special characters in URLs.
  • The basic attributes of <form> are action and method.
  • The basic attributes of <input> are type, name, and size.
  • The basic attribute of <button> is type.

What now?

Let’s see how you can write PHP to handle form data.

Form data in PHP

Where are we?

We just looked at the HTML tags <form>, <input>, and <button>, and saw how browsers send form data to Web servers. Let’s see how you can retrieve that data using PHP.

This lesson’s goals

By the end of this lesson, you should:

  • Know how PHP fetches form data.
  • Know how to fetch data from post and get forms.

Retrieving form data

Here’s some HTML from the previous lesson.

<h1>Simple Form</h1>
<form action="process-simple-form-post.php" method="post">
  <p>First name:
    <input name="first_name" type="text" size="20">
  </p>
  <p>Surname:
    <input name="surname" type="text" size="20">
  </p>
  <p>
    <button type="submit">Save</button>
  </p>
</form>

Figure 1. Simple form HTML

When the user clicks the button, the browser gets the data from the form, and sends it to the page given in the form’s action attribute. That’s process-simple-form-post.php.

You can try it.

Here’s process-simple-form-post.php.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title></title>
  </head>
  <body>
    <?php
    $first_name = $_POST['first_name'];
    $surname = $_POST['surname'];
    ?>
    <p>Your name is <?php print $first_name . ' ' . $surname; ?>.</p>
  </body>
</html>

Figure 2. process-simple-form-post.php

Line 9 fetches the data for one of the fields and puts it into a variable. Here is the statement again:

Fetching from $_POST

Figure 3. Fetching from $_POST

$_POST is an array holding all of the form data. You don’t need to know much about arrays yet; just follow the pattern above.

In the [''], you give the name of the HTML input field. This was specified in the HTML:

<input name="first_name" type="text" size="20">

There is a variable name in Figure 3. That’s where the form data will go.

You can name the PHP variable anything you like. Common practice is to give it the same name as the HTML form field. This makes it easier to match the HTML code with the PHP code.

Line 10 fetches the other form field’s data. It works the same way.

Line 12 in Figure 2 outputs the values. As before, print just inserts stuff into the PHP program’s output stream. Let’s look at this:

$first_name . ' ' . $surname

It’s the string concatenation operator at work again. The line tells PHP to:

Take the contents of $first_name, stick a space on the end of that, and stick the contents of $surname on the end of that.

The space (’ ‘ in the statement) is a string constant. The characters between the quotes are used exactly as-is, with no changes. For example:

$first_name . ' (Killer) ' . $surname

If $first_name was “Bugs” and $surname was “Bunny”, you would get:

Bugs (Killer) Bunny

The spaces inside the quotes are important. If we left them out:

$first_name . '(Killer)' . $surname

We’d get:

Bugs(Killer)Bunny

The spaces outside the quotes don’t matter to the PHP interpreter. We could have:

$first_name.' (Killer) '.$surname

It would still work. Some people think the extra spaces make the line more readable.

Single versus double quotes

Here’s part of line 12 again:

print $first_name . ' ' . $surname;

We could have written it like this:

print "$first_name $surname";

This version has double quotes. What’s the difference?

  • When PHP sees single quotes ('), it returns exactly what is between the quotes, with no changes.
  • When PHP sees double quotes ("), it replaces variable names with their contents, and then returns the result.

JavaScript doesn’t do this. Only PHP.

Here are some more examples.

<?php
$a = 'Willow';
$b = 'Rosenberg';
print "<p>$a $b</p>";
  //Prints <p>Willow Rosenberg</p>
print '<p>$a $b</p>';
  //Prints <p>$a $b</p>
print '<p>'. $a . ' ' . $b . '</p>';
  //Prints <p>Willow Rosenberg</p>
?>

Figure 4. Single versus double quotes

You can try it.

Post or get?

Here’s one of those statements again:

$first_name = $_POST['first_name'];

That only works for forms that use method="post":

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

If you used get:

<form action="..." method="get">

then you fetch the form data in PHP like this:

$first_name = $_GET['first_name'];

If your PHP code isn’t fetching form data, check that you are using the right method.

Exercise: Address form data

In a previous exercise, you created a form like this:

Address form

Figure 1. Address form

Add a PHP page that processes this data, producing something like:

Address output

Figure 2. Address output

You can try my solution. You can also download the files.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Summary

  • Use $_POST[‘name’] to fetch data from forms submitted with the post method.
  • Use $_GET[‘name’] to fetch data from forms submitted with the get method.

What now?

Let’s see how you deal with an annoying thing PHP does to quotes in form data.

Magic quotes and strings

Where are we?

You know how to get form data into a PHP program. Let’s talk about an annoying thing that PHP does to text strings.

This lesson’s goals

In this lesson, you learn:

  • That PHP’s magic quotes feature adds extra backslashes to text.
  • How to use the stripslashes() function to fix the problem.

Strings with quotes

Look at the name form again. Here it is, with some data:

Input

Figure 1. Input

When the user clicks the button, the form data is sent to this page:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title></title>
  </head>
  <body>
    <?php
    $first_name = $_POST['first_name'];
    $surname = $_POST['surname'];
    ?>
    <p>Your name is <?php print $first_name . ' ' . $surname; ?>.</p>
  </body>
</html>

Figure 2. Process form data

Here is the output:

Output

Figure 3. Output

No problem.

But suppose the user has a name with a quote (’) in it, like this:

Input with quote

Figure 4. Input with quote

This is the result:

Output with quote

Figure 5. Output with quote

There’s a backslash in the output (\). You can try it.

Huh? Where did that backslash come from?

The magic quotes setting

PHP has a bunch of settings that change how it works. For example, you can set the maximum time a PHP program is allowed to run.

One of the settings is “magic quotes.” It’s either on or off. When it’s on, PHP looks at all the text data coming in from forms. If it finds a quote, it will put a backslash in front of it. So it converts De'ev to De\'ev.

If magic quotes is off, no conversion happens. De'ev stays De'ev.

Here’s the output again:

Output with quote

Figure 4 (again). Output with quote

This came from a PHP program running on a server. The server had magic quotes on. Hence the backslash.

I turned magic quotes off, and ran the program again. I got:

No backslash

Figure 5. No backslash

Renata
Renata

Er, why did the PHP people do this magic quotes thing?

Kieran
Kieran

It helps with security in some situations. But it causes problems, as well. For De’ev, and others.

Many people think that magic quotes was a bad idea. It didn’t solve many security problems. And anyway, there are better ways to handle those security issues it did solve.

Magic quotes will be dropped in the next major version of PHP.

Getting rid of the backslashes

There are two ways to get rid of the extra backslashes. One way is to turn the magic quotes setting off in PHP. But to do that, you need access to a special settings file. You may or may not have access, depending on your hosting account.

The second way is to call PHP’s stripslashes() function. It does what its name says. You give it a string, and it goes through and removes the backslashes.

Here’s the code again, with a slight change:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title></title>
  </head>
  <body>
    <?php
    $first_name = $_POST['first_name'];
    $first_name = stripslashes($first_name);
    $surname = $_POST['surname'];
    $surname = stripslashes($surname);
    ?>
    <p>Your name is <?php print $first_name . ' ' . $surname; ?>.</p>
  </body>
</html>

Figure 6. Using stripslashes()

Lines 10 strips out the slashes from $first_name, and puts the result back into $first_name. Line 12 does the same for $surname.

You could also write it like this:

<?php
$first_name = stripslashes($_POST['first_name']);
$surname = stripslashes($_POST['surname']);
?>
<p>Your name is <?php print $first_name . ' ' . $surname; ?>.</p>

Figure 7. Using stripslashes() again

It works the same. Line 9 takes the value of the form field first_name, strips out the backslashes, and puts the result into $first_name.

You could also do this:

<?php
$first_name = $_POST['first_name'];
$surname = $_POST['surname'];
?>
<p>Your name is <?php print stripslashes($first_name) . ' ' . stripslashes($surname); ?>.</p>

Figure 8. Using stripslashes() again again

This version moves the calls to stripslashes() to the output.

Exercise: Remove the slashes

Write an HTML page with a form that has one field, like this:

Input

Figure 1. Input

When the button is clicked, the data is sent to a PHP page that shows whatever data the user typed. If there is a quote (’) in the data, no slashes appear in the output. Like this:

Output

Figure 2. Output

You can try my solution to see how it works. You can download my solution, but do the exercise yourself before you look at the files.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Summary

In this lesson, you learned:

  • That PHP’s magic quotes feature adds extra backslashes to text.
  • How to use the stripslashes() function to fix the problem.

What now?

Let’s see how you can do computations on form data.

Doing computations

Where are we?

You know how to create forms, and get user input into PHP programs. Now let’s do something with the data.

This lesson’s goals

By the end of this lesson, you should:

  • Know how to use PHP variables in computations.
  • Be able to control format of output numbers.
  • Handle radio button input.

A simple order form

Suppose we start a company that sells two dog toys, frisbees and giant chew ropes. Frisbees are the great flying disks from Wham-o. Many dogs love chasing frisbees!

We want to sell the toys over the Web. Let’s create a form like this:

Order form

Figure 1. Order form

The user enters the number of each item s/he wants to order:

Order form with data

Figure 2. Order form with data

The user clicks the button, and a confirmation page appears.

Order confirmation

Figure 3. Order confirmation

We’ll fix the number formats later.

Here’s the HTML for the order form.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>Simple Order Form</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  </head>
  <body>
    <h1>Simple Order Form</h1>
    <form action="process-order.php" method="post">
      <p>
        Frisbees:
        <input type="text" name="frisbees" size="3">
        at $8.95 each
      </p>
      <p>
        Giant chew ropes:
        <input type="text" name="giant_chew_ropes" size="3">
        at $12.95 each
      </p>
      <p>
        <button type="submit">Order</button>
      </p>
    </form>
  </body>
</html>

Figure 4. Order form HTML

Nothing new here. Just two text input fields, as before. One field is for the number of frisbees the user wants. The other is for the number of giant chew ropes.

Here’s the code for process-order.php, the file listed in the action attribute of the form.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Order Processed</title>
  </head>
  <body>
    <h1>Order Processed</h1>
    <?php
    //Get the input.
    $frisbees = $_POST['frisbees'];
    $giant_chew_ropes = $_POST['giant_chew_ropes'];
    //Compute totals.
    $frisbees_total = $frisbees * 8.95;
    $giant_chew_ropes_total = $giant_chew_ropes * 12.95;
    $order_total = $frisbees_total + $giant_chew_ropes_total;
    //Output totals.
    ?>
    <p>Thank you for your order.</p>
    <table cellpadding="5" cellspacing="0" border="1">
      <tr>
        <th>Product</th>
        <th>Number ordered</th>
        <th>Unit price</th>
        <th>Total price</th>
      </tr>
      <tr>
        <td>Frisbees</td>
        <td><?php print $frisbees; ?></td>
        <td>$8.95</td>
        <td>$<?php print $frisbees_total; ?></td>
      </tr>
      <tr>
        <td>Giant chew ropes</td>
        <td><?php print $giant_chew_ropes; ?></td>
        <td>$12.95</td>
        <td>$<?php print $giant_chew_ropes_total; ?></td>
      </tr>
      <tr>
        <td colspan="3">Total</td>
        <td>$<?php print $order_total; ?></td>
      </tr>
    </table>
  </body>
</html>

Figure 5. Order processing code

Lines 11 and 12 fetch the data from the form, and put them into PHP variables:

$frisbees = $_POST['frisbees'];
$giant_chew_ropes = $_POST['giant_chew_ropes'];

Line 14 works out the total cost of the frisbees:

$frisbees_total = $frisbees * 8.95;

It’s the number of frisbees ordered (in $frisbees) times the price of one frisbee (8.95). The asterisk (*) means “multiply.” The result is put into $frisbees_total.

Line 15 works out the total cost of the giant chew ropes:

$giant_chew_ropes_total = $giant_chew_ropes * 12.95;

It’s the number of giant chew ropes ordered (in $giant_chew_ropes) times the price of one giant chew rope ($12.95). The result is put into $giant_chew_ropes_total.

Line 16 works out the total cost of the order:

$order_total = $frisbees_total + $giant_chew_ropes_total;

It’s the total cost of the frisbees (in $frisbees_total) plus the total cost of the giant chew ropes (in $giant_chew_ropes_total). The order total is put into the variable $order_total.

The results are output in a <table>. You learned about tables in the lesson A Web page with tables.

Exercise: Circle area

Write a program that computes the area of a circle. Create a form like this:

Form

Figure 1. Form

The user enters a number, and clicks the button:

Form with data

Figure 2. Form with data

The user then sees:

Output

Figure 3. Output

The formula is:

area = 3.14159 x radius x radius

You can try my solution, and download the files. Of course, try it yourself first.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Fixing the number formats

We’ve seen strange number formats, like this:

Order confirmation

Figure 3 (again). Order confirmation

The prices are messed up. For example, 17.9 should be 17.90.

This is easy to fix with the number_format() function. You tell it the number you want to format and how many decimals you want, and it will return a formatted value. For example:

$x = 17.9;
print number_format($x, 2);

This will output 17.90.

We can change the order processing program like this:

<tr>
  <td>Frisbees</td>
  <td><?php print $frisbees; ?></td>
  <td>$8.95</td>
  <td>$<?php print number_format($frisbees_total, 2); ?></td>
</tr>
<tr>
  <td>Giant chew ropes</td>
  <td><?php print $giant_chew_ropes; ?></td>
  <td>$12.95</td>
  <td>$<?php print number_format($giant_chew_ropes_total, 2); ?></td>
</tr>
<tr>
  <td colspan="3">Total</td>
  <td>$<?php print number_format($order_total, 2); ?></td>
</tr>

Figure 6. Formatting numbers

You can try it.

Exercise: Cylinder volume

Write a program that computes the volume of a cylinder. Create a form like this:

Form

Figure 1. Form

When the user clicks the button, the result appears:

Output

Figure 2. Output

Make sure that the volume is shown to three decimal places.

You can try my solution. You can download the files. Try it yourself first, of course.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Adding shipping

Let’s add shipping to our form.

Order form with shipping

Figure 7. Order form with shipping

The form uses radio buttons for the shipping method. The user can select only one. You can try it.

Here’s the output:

Order confirmation with shipping

Figure 8. Order confirmation with shipping

Here’s the new HTML.

<div>
  <p>Shipping method</p>
  <p>
    <input type="radio" name="shipping_method" value="standard">
    Standard ($5)
  </p>
  <p>
    <input type="radio" name="shipping_method" value="overnight">
    Overnight ($10)
  </p>
</div>

Figure 9. HTML for shipping method

type="radio" tells the browser you want to use a radio button.

Only one of the radio buttons can be selected. When one is clicked, the other is turned off.

There can be more than one group of radio buttons on a form. Like this:

Radio button groups

Figure 10. Radio button groups

The user can select one button in each group:

Selected buttons

Figure 11. Selected buttons

If the user clicks on a radio button, the others are turned off. But which others? Only the ones in the same group.

Selecting different buttons

Figure 12. Selecting different buttons

How does the browser know which radio buttons belong together? Here’s the HTML:

<p>Favorite animal</p>
<blockquote>
  <input type="radio" name="animal" value="Dog">Dog<br>
  <input type="radio" name="animal" value="Cat">Cat<br>
  <input type="radio" name="animal" value="Horse">Horse<br>
  <input type="radio" name="animal" value="Maggot">Maggot<br>
</blockquote>
<p>Favorite color</p>
<blockquote>
  <input type="radio" name="color" value="Green">Green<br>
  <input type="radio" name="color" value="Blue">Blue<br>
  <input type="radio" name="color" value="Purple">Purple<br>
</blockquote>

Figure 13. Radio button HTML

The name attribute of the radio buttons defines the groups. Radio buttons what belong together have the same name.

Let’s go back to the shipping method for the dog toys. Here is the HTML:

<div>
  <p>Shipping method</p>
  <p>
    <input type="radio" name="shipping_method" value="standard">
    Standard ($5)
  </p>
  <p>
    <input type="radio" name="shipping_method" value="overnight">
    Overnight ($10)
  </p>
</div>

Figure 9 (again). HTML for shipping method

Both radio buttons have the same name: shipping_method (lines 24 and 28). That’s how the browser knows they belong together.

The PHP page will get one piece of form data called shipping_method. It’s value will be either standard or overnight. Which one the PHP gets will depend on what the user chose.

Here’s the PHP page.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Order Processed</title>
  </head>
  <body>
    <h1>Order Processed</h1>
    <?php
    //Get the input.
    $frisbees = $_POST['frisbees'];
    $giant_chew_ropes = $_POST['giant_chew_ropes'];
    $shipping_method = $_POST['shipping_method'];
    //Compute product totals.
    $frisbees_total = $frisbees * 8.95;
    $giant_chew_ropes_total = $giant_chew_ropes * 12.95;
    //Compute shipping cost.
    if ( $shipping_method == 'standard' ) {
      $shipping_cost = 5;
    }
    else {
      $shipping_cost = 10;
    }
    $order_total = $frisbees_total 
      + $giant_chew_ropes_total
      + $shipping_cost;
    //Output totals.
    ?>
    <p>Thank you for your order.</p>
    <table cellpadding="5" cellspacing="0" border="1">
      <tr>
        <th>Product</th>
        <th>Number ordered</th>
        <th>Unit price</th>
        <th>Total price</th>
      </tr>
      <tr>
        <td>Frisbees</td>
        <td><?php print $frisbees; ?></td>
        <td>$8.95</td>
        <td>$<?php print number_format($frisbees_total, 2); ?></td>
      </tr>
      <tr>
        <td>Giant chew ropes</td>
        <td><?php print $giant_chew_ropes; ?></td>
        <td>$12.95</td>
        <td>$<?php print number_format($giant_chew_ropes_total, 2); ?></td>
      </tr>
      <tr>
        <td colspan="3">Shipping</td>
        <td>$<?php print number_format($shipping_cost, 2); ?></td>
      </tr>
      <tr>
        <td colspan="3">Total</td>
        <td>$<?php print number_format($order_total, 2); ?></td>
      </tr>
    </table>
  </body>
</html>

Figure 14. Code for PHP file

Line 13 gets the shipping_method. Lines 18 to 23 work out the shipping cost.

PHP’s if statement is much like JavaScript’s if statement, that we covered earlier. The general form is:

if ( expression ) {
    Do this if expression is true;
}
else {
    Do this if expression is false;
}

In line 18,

$shipping_method == 'standard'

is true if $shipping_method has exactly “standard” in it. Not “STANDARD” or “Standard” or “ standard “ – just “standard”.

Note the ==. Don’t use just =. = means “take the thing on the right and put it in the variable on the left.” Like lines 11, 12, 13, 15, 16, etc. If you want to compare, use ==.

You can use other things besides ==. For example:

if ( age > 21 ) {
if ( age <= 65 ) {
if ( color != 'blue') {

> is greater than. <= is less than or equal to. != means “is not equal to.”

Summary

You learned:

  • Know how to use PHP variables in computations.
  • Be able to control format of output numbers.
  • Handle radio button input.

What now?

Time for some exercises.

Exercises: Fundamental forms

Exercise: Order ship models

Create an order form for model ships. The form should look like this:

Order form

Figure 1. Order form

After clicking the button, you see:

Output

Figure 2. Output

You can try my solution. You can also download the files. Try it yourself first, of course.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?