facebook google plus twitter
Webucator's Free PHP Tutorial

Lesson: PHP and HTML Forms

Welcome to our free PHP tutorial. This tutorial is based on Webucator's Introduction to PHP Training course.

In this lesson, you will learn how to process form data in PHP.

Lesson Goals

  • Process form data with PHP.

HTML Forms

How HTML Forms Work

A very common way to pass data from one page to another is through HTML forms. There are two methods of submitting data through a form: the get method and the post method. The method used is determined by the value of the method attribute of the form tag. The default method is get.

Get Method

When the get method is used, data is sent to the server in name-value pairs as part of the query string. The get method is most commonly used by search pages and is useful when it is important to be able to bookmark the resulting page (i.e, the page that is returned after the form is submitted).

Post Method

When the post method is used, data is sent to the server in name-value pairs behind the scenes. The two major advantages of the post method are:

  • The name-value pairs are not visible in the location bar, so sensitive data such as passwords are not displayed on the screen.
  • Files, such as images and Office documents, can be uploaded via the form.

The major disadvantage is that the resulting page cannot be bookmarked.

A Sample HTML Form

The following is a sample HTML form for inserting an employee record into a database.

Code Sample:

Forms/Demos/AddEmployee.php
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Add Employee</title>
</head>
<body>
<h1>Add Employee</h1>
<form method="post" action="ProcessEmployee.php">
<table>
	<tr>
		<td>First name:</td>
		<td><input type="text" name="FirstName" size="15"></td>
	</tr>
	<tr>
		<td>Last name:</td>
		<td><input type="text" name="LastName" size="15"></td>
	</tr>
	<tr>
		<td>Title:</td>
		<td><input type="text" name="Title" size="30"></td>
	</tr>
	<tr>
		<td>Title of Courtesy:</td>
		<td>
			<input type="radio" name="TitleOfCourtesy" value="Dr.">Dr.
			<input type="radio" name="TitleOfCourtesy" value="Mr.">Mr.
			<input type="radio" name="TitleOfCourtesy" value="Mrs.">Mrs.
			<input type="radio" name="TitleOfCourtesy" value="Ms.">Ms.
		</td>
	</tr>
	<tr>
		<td>Birth date:</td>
		<td>
			<select name="BirthMonth">
				<option value="1">January</option>
				<option value="2">February</option>
				<option value="3">March</option>
				<option value="4">April</option>
				<option value="5">May</option>
				<option value="6">June</option>
				<option value="7">July</option>
				<option value="8">August</option>
				<option value="9">September</option>
				<option value="10">October</option>
				<option value="11">November</option>
				<option value="12">December</option>
			</select>
			<select name="BirthDay">
			<?php
				for ($i=1; $i<=31; $i++)
				{
					echo "<option value='$i'>$i</option>";
				}
			?>
			</select>
			<select name="BirthYear">
			<?php
				for ($i=2011; $i>=1900; $i=$i-1)
				{
					echo "<option value='$i'>$i</option>";
				}
			?>
			</select>
		</td>
	</tr>
	<tr>
		<td>Hire date:</td>
		<td>
			<select name="HireMonth">
				<option value="1">January</option>
				<option value="2">February</option>
				<option value="3">March</option>
				<option value="4">April</option>
				<option value="5">May</option>
				<option value="6">June</option>
				<option value="7">July</option>
				<option value="8">August</option>
				<option value="9">September</option>
				<option value="10">October</option>
				<option value="11">November</option>
				<option value="12">December</option>
			</select>
			<select name="HireDay">
			<?php
				for ($i=1; $i<=31; $i++)
				{
					echo "<option value='$i'>$i</option>";
				}
			?>
			</select>
			<select name="HireYear">
			<?php
				for ($i=2011; $i>=1992; $i=$i-1)
				{
					echo "<option value='$i'>$i</option>";
				}
			?>
			</select>
		</td>
	</tr>
	<tr>
		<td>Address:</td>
		<td><input type="text" name="Address" size="50"></td>
	</tr>
	<tr>
		<td>City:</td>
		<td><input type="text" name="City" size="30"></td>
	</tr>
	<tr>
		<td>Region:</td>
		<td><input type="text" name="Region" size="2"></td>
	</tr>
	<tr>
		<td>Postal Code:</td>
		<td><input type="text" name="PostalCode" size="10"></td>
	</tr>
	<tr>
		<td>Country:</td>
		<td><input type="text" name="Country" size="5"></td>
	</tr>
	<tr>
		<td>Home Phone:</td>
		<td><input type="text" name="HomePhone" size="15"></td>
	</tr>
	<tr>
		<td>Extension:</td>
		<td><input type="text" name="Extension" size="5"></td>
	</tr>
	<tr>
		<td colspan="2">Notes:</td>
	</tr>
	<tr>
		<td colspan="2">
			<textarea name="Notes" cols="50" rows="3"></textarea>
		</td>
	</tr>
	<tr>
		<td>Manager:</td>
		<td>
			<select name="ReportsTo">
				<option value="0">Choose...</option>
				<option value="1">Nancy Davolio</option>
				<option value="2">Andrew Fuller</option>
				<option value="3">Janet Leverling</option>
				<option value="4">Margaret Peacock</option>
				<option value="5">Steven Buchanan</option>
				<option value="6">Michael Suyama</option>
				<option value="7">Robert King</option>
				<option value="8">Laura Callahan</option>
				<option value="9">Anne Dodsworth</option>
			</select>
		</td>
	</tr>
	<tr>
		<td>Password:</td>
		<td><input type="password" name="Password1" size="10"></td>
	</tr>
	<tr>
		<td>Repeat Password:</td>
		<td><input type="password" name="Password2" size="10"></td>
	</tr>
	<tr>
		<td colspan="2"><input type="submit" value="Add Employee"></td>
	</tr>
</table>
</form>
</body>
</html>

The above code, which contains some embedded PHP code, outputs a simple HTML form. Its action page is ProcessEmployee.php, which will eventually contain PHP code to process the submitted form.

Form Variables

Form variables are variables that are created when an HTML form is submitted using the post method. These variables are stored in the $_POST superglobal array. Here are a few things you should know about how HTML forms are processed:

  1. If a text field or textarea is left blank, the variable is sent to the server with a value of "" (empty string).
  2. Select menus always send a variable to the server (unless they have been disabled in some way).
  3. If no radio button in a radio array is checked, no variable for that radio array is sent to the server.
  4. If a checkbox is not checked, no value is sent to the server. If it is checked, the default value of "on" is sent unless otherwise set in the HTML.
  5. If the submit button has a name (e.g, <input type="submit" name="Inserting" value="Add Employee"/>), when that submit button is clicked a variable by that name with the corresponding value will be sent to the server.

Processing Form Input

Duration: 40 to 50 minutes.

In this exercise, you will create a page that processes the form data. The form entry page, Exercises/AddEmployee.php, is already complete and is identical to Demos/AddEmployee.php. Filled out, the form would look like this:Add Employee Form

If everything is filled out correctly, the page should display as follows:Process Employee Filled Out

If all fields are left blank except for the password fields, which contain two different values, the page should display as follows:Process Employee Not Filled Out

  1. Open Forms/Exercises/ProcessEmployee.php in your editor.
  2. For each form entry (other than the dates, which we'll worry about later), create a simple global variable to hold...
    • either an error if the entry is not filled out or filled out incorrectly.
    • or the value entered.
  3. Output the variables as list items as shown in the screenshots above.
  4. Save your work.
  5. To test your solution, load Forms/Exercises/AddEmployee.php in the browser and fill out and submit the form.

Code Sample:

Forms/Exercises/ProcessEmployee.php
<?php
	//For each entry coming through the form,
	//  create a simple global variable to hold...
	//	- either an error if the entry is not filled or filled incorrectly
	//	- or the value entered.
	//The first one is done for you.

	if ($_POST['FirstName'] == '')
	{
		$firstName = '<span style="color:red;">First name omitted.</span>';
	}
	else
	{
		$firstName = $_POST['FirstName'];
	}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Process Employee</title>
</head>
<body>
	<h1>Process Employee</h1>
	<ul>
	<?php
	//Output the variables as list items.
	//Part of the first one is done for you.
		echo "<li><b>Name:</b> $firstName</li>";
	?>
	</ul>
</body>
</html>

Challenge

If there are any errors, include a link at the bottom that directs the user to the form. If there are no errors, include a form full of hidden fields containing the values entered and a submit button that reads "Confirm".

Solution:

Forms/Solutions/ProcessEmployee.php
<?php
	if ($_POST['FirstName'] == '')
	{
		$firstName = '<span style="color:red;">First name omitted.</span>';
	}
	else
	{
		$firstName = $_POST['FirstName'];
	}
	
	if ($_POST['LastName'] == '')
	{
		$lastName = '<span style="color:red;">Last name omitted.</span>';
	}
	else
	{
		$lastName = $_POST['LastName'];
	}

	if ($_POST['Title'] == '')
	{
		$title = '<span style="color:red;">Title omitted.</span>';;
	}
	else
	{
		$title = $_POST['Title'];
	}

	if ( array_key_exists('TitleOfCourtesy',$_POST) )
	{
		$titleOfCourtesy = $_POST['TitleOfCourtesy'];
	}
	else
	{
		$titleOfCourtesy = '<span style="color:red;">
			Title of Courtesy not selected.</span>';
	}

	if ($_POST['Address'] == '')
	{
		$address = '<span style="color:red;">Address omitted.</span>';
	}
	else
	{
		$address = $_POST['Address'];
	}

	if ($_POST['City'] == '')
	{
		$city = '<span style="color:red;">City omitted.</span>';
	}
	else
	{
		$city = $_POST['City'];
	}

	if ($_POST['Region'] == '')
	{
		$region = '<span style="color:red;">Region omitted.</span>';
	}
	else
	{
		$region = $_POST['Region'];
	}

	if ($_POST['PostalCode'] == '')
	{
		$postalCode = '<span style="color:red;">Postal code omitted.</span>';
	}
	else
	{
		$postalCode = $_POST['PostalCode'];
	}

	if ($_POST['Country'] == '')
	{
		$country = '<span style="color:red;">Country omitted.</span>';
	}
	else
	{
		$country = $_POST['Country'];
	}

	if ($_POST['HomePhone'] == '')
	{
		$homePhone = '<span style="color:red;">Home phone omitted.</span>';
	}
	else
	{
		$homePhone = $_POST['HomePhone'];
	}

	if ($_POST['Extension'] == '')
	{
		$extension = '<span style="color:red;">Extension omitted.</span>';
	}
	else
	{
		$extension = $_POST['Extension'];
	}

	if ($_POST['Notes'] == '')
	{
		$notes = 'none';
	}
	else
	{
		$notes = $_POST['Notes'];
	}

	if ($_POST['ReportsTo'] == 0)
	{
		$reportsTo = '<span style="color:red;">Manager not selected.</span>';
	}
	else
	{
		$reportsTo = $_POST['ReportsTo'];
	}

	if ($_POST['Password1'] == $_POST['Password2'])
	{
		$password = $_POST['Password1'];
	}
	else
	{
		$password = '<span style="color:red;">Passwords do not match.</span>';
	}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Process Employee</title>
</head>
<body>
	<h1>Process Employee</h1>
	<ul>
	<?php
		echo "<li><b>Name:</b> $titleOfCourtesy $firstName $lastName</li>";
		echo "<li><b>Title:</b> $title</li>";
		echo "<li><b>Address:</b> $address</li>";
		echo "<li><b>City, Region Zip:</b> $city, $region $postalCode</li>";
		echo "<li><b>Country:</b> $country</li>";
		echo "<li><b>Home phone:</b> $homePhone</li>";
		echo "<li><b>Extension:</b> $extension</li>";
		echo "<li><b>Notes:</b> $notes</li>";
		echo "<li><b>Manager:</b> $reportsTo</li>";
		echo "<li><b>Password:</b> $password</li>";
	?>
	</ul>
</body>
</html>

Challenge Solution:

Forms/Solutions/ProcessEmployee-challenge.php
<?php
	$errors = false;
	if ($_POST['FirstName'] == '')
	{
		$firstName = '<span style="color:red;">First name omitted.</span>';
		$errors = true;
	}
	else
	{
		$firstName = $_POST['FirstName'];
	}
---- C O D E   O M I T T E D ----
if ($errors)
	{
		echo '<a href="javascript:history.go(-1)">Please go back to the
					form and try again.</a>';
	}
	else
	{
	?>
	<form method="post" action="CompleteProcessForm.php">
	<input type="hidden" name="FirstName" value="<?php echo $firstName ?>">
	<input type="hidden" name="LastName" value="<?php echo $lastName ?>">
	<input type="hidden" name="Title" value="<?php echo $title ?>">
	<input type="hidden" name="TitleOfCourtesy"	value="<?php echo $titleOfCourtesy ?>">
	<input type="hidden" name="Address" value="<?php echo $address ?>">
	<input type="hidden" name="City" value="<?php echo $city ?>">
	<input type="hidden" name="Region" value="<?php echo $region ?>">
	<input type="hidden" name="PostalCode" value="<?php echo $postalCode ?>">
	<input type="hidden" name="Country" value="<?php echo $country ?>">
	<input type="hidden" name="HomePhone" value="<?php echo $homePhone ?>">
	<input type="hidden" name="Extension" value="<?php echo $extension ?>">
	<input type="hidden" name="Notes" value="<?php echo $notes ?>">
	<input type="hidden" name="ReportsTo" value="<?php echo $reportsTo ?>">
	<input type="hidden" name="Password" value="<?php echo $password ?>">
	<input type="submit" value="Confirm">
	</form>
	<?php
	}
	?>
</body>
</html>