Building a Form






Building a Form

Since you'll need a place for the user to enter a search query, let's begin by building a form to handle the user's input. Every form must have these basic components:

  • The submission type defined with the method keyword

  • One or more input elements defined with the input tag

  • The destination to go to when submitted defined with the action keyword

Let's build a simple form with a text input field called search and a submit button, as shown in Figure.

A simple form example

 1 <html>
 2 <head>
 3  <title>Building a Form</title>
 4 </head>
 5 <body>
 6  <form action="<?php echo($_SERVER['PHP_SELF']); ?>"
 7        method="get">
 8   <label>
 9         Search: <input type="text" name="search" />
 10    </label>
 11      <input type="submit" value="Go!" />
 12  </form>
 13 </body>
 14 </html>

Place the code in Figure into a file called simple.php in a web-accessible directory on your web server, such as the document root. Strictly speaking, forms are defined purely by HTML, but we're using some PHP code on line 6 to reference the super global PHP_SELF. This provides a shortcut to the name of the current PHP file that handles the submission of the form data.

The form in Figure allows you to capture the search sting from the user for a search. Notice how we wrapped a label tag around the input where the text was; this makes the form easier to use. Since clicking on the Search: text automatically sends the cursor to the search field. On line 7, we set the form submission method to GET. This is done to insure that users can bookmark their searches and not have to come back to the page and reenter their data. Line 9 does the bulk of the work by defining the text field.

Accessing the simple.php file from your browser should generate a form similar to Figure. It's not terribly useful, as any value you submit just brings the same form back again, but we'll take care of that soon.

How the sample form appears in your browser


Accessing Submitted Form Values

Let's go ahead and modify the code in Figure to display back the search string when the form is submitted. To do this, check the value of a GET submitted field with the syntax $_GET[field]. Likewise, $_POST[field] is used to access a field when using the POST field submission.

Since search is the name of the field that we specified when building the form, we'll use $_GET["search"] in Figure.

Modifying our simple search to process the results

<html>
<head>
  <title>Building a Form</title>
</head>
<body>
<?php
$search = $_GET["search"];
$self=$_SERVER['PHP_SELF'];
if ($search != NULL )
{
('
<form action="'.$_SERVER["PHP_SELF"].'" method="GET">
<label>Search: <input type="text" name="search" />
</label>
<input type="submit" value="Go!" />

         </form>
        ');
}
?>
</body>
</html>

Figure generates this HTML:

<html>
<head>
  <title>Building a Form</title>
</head>
<body>
<form action="/oreilly/ch10/simple.php" method="GET" />
         <label> Search: <input type="text" name="search" id="search"> </label>
         <input type="submit" value="Go!" />
         </form>

        </body>
</html>

If you submitted a value of PHP in the search text box, you'd get output similar to Figure.

The same script is now able to echo back the search string


When the form is submitted, the if statement notices that the $search variable has a value assigned. Instead of the script returning the HTML form, the search string is returned. So, you have the same PHP file generating the form and processing its submitted values.

With forms, you can specify default values and use different form inputs. There are various ways you can submit the form. These will be explained in the following subsections.

Default Values

When doing searches on a database, you might need to actually have some default values in your forms. This is useful, for example, for searching within a price range. The user doesn't always want to insert values, and it makes it that much simpler when searching. Typically, the default value for a form element is set with the value attribute; there is an exception for checkboxes that use the checked keyword. Take Figure.

Form default values

<html>
<head>
  <title>Form Default Values</title>
</head>
<body>
  <form action="<?php echo($_SERVER['PHP_SELF']); ?>" method="GET" />
    <label>Min Price <input type="text" name="min_price" value="0" /></label><br />
    <label>Max Price <input type="text" name="max_price" value="1000" /></label>
<br />
    <input type="submit" value="Go! />
  </form>
</body>
</html>

In Figure, the default values reflect 0 and 1000 for the minimum and maximum prices that you want to search. Depending on the area, if the user searches for an apartment to rent, this is a good starting point. We already specified a default value for the submit button as Go! in Figure.

The default values appear in their fields


Types of Input

There are many different types of input, so which one should you use? Radio buttons, checkboxes, text, input, text areas buttons . . . oh my! We'll describe each of our input options.

Text boxes

Most of the time when dealing with input from a user, you might want a string of text. A text type element is used to capture these strings from the user. The name attribute is required to process the input after a form submission as it specifies how to reference the value. When it appears in the browser, the size parameter determines the length of the text box. The maxlength parameter determines the maximum number of characters the user can place in the field. The syntax is:

<input type="text" name="name" size="display size" maxlength="max characters allows" />

For example, the following:

<form>
<input type="text" name="search" size="10" maxlength="30" />
</form>

creates a text box like Figure.

Text areas

If you need a large chunk of text from a user or are going to be using a WYSIWYG editor, you need to use a text area. A text area is defined by using the textarea element. The name, cols, and rows attributes are required. The name attribute works like it did in a text box. The cols attribute specifies how many columns to create for your text area. The rows attribute specifies how many rows to create. The syntax is:

<textarea name="name" cols="# of cols" rows="# of rows"></textarea>

For example:

<form>
<label>Suggestion: <textarea name="suggestions" cols="40" rows="5"></textarea>
</label>
<input type="submit" value="Go! />
</form>

might display like Figure.

A simple form with a text area element


Checkboxes

A checkbox is useful when you want to give users several different options, especially when they're allowed to select each choice individually. Use checkboxes only when you have a few options to give to a user; otherwise, there is a different type of input that you would want to use. This is called a select, which we'll talk about in a bit. For a checkbox, set the input type to checkbox. The name and value attributes are also required. If the value is set to checked, the checkbox is checked by default.

The syntax is:

<input type="checkbox" name="name" value="checkbox value" />

For example:

<form>
<fieldset>
<label>Italian <input type="checkbox" name="food[]" value="Italian" /></label>
<label>Mexican <input type="checkbox" name="food[]" value="Mexican" /></label>
<label>Chinese <input type="checkbox" name="food[]" value="Chinese"
checked="checked" /></label>
</fieldset>
<input type="submit" value="Go! />
</form>

This displays the box shown in Figure.

A sample form with checkboxes


Radio buttons

Radio buttons behave just like the presets on a radio. They are like checkboxes, except you can only select one radio button at a time. To create a radio button, set the type to radio. The name and value attributes are required. All of the radio buttons in a group must use the same name to allow for only one value. The syntax is:

<input type="radio" name="name" value="radio button value" />

For example:

<form>
<fieldset>
<label>Italian <input type="radio" name="food" value="Italian" /></label>
<label>Mexican <input type="radio" name="food" value="Mexican" /></label>
<label>Chinese <input type="radio" name="food" value="Chinese"
checked="checked"  /></label>
</fieldset>
<input type="submit" value="Go! />
</form>

This looks like Figure.

The same choices are available as before, but the radio buttons are round


Figure allows only one type of food to be selected.

Hidden

Hidden form elements allow you to send information from the form to the script that processes the data without that information being visible to the user. This may be information such as whether the forms' submit button was pressed, or perhaps a username. The syntax is:

<input type="hidden" name="name" value="hidden value" />

For example:

<form>
<input type="hidden" name="submitted" value="true" />
</form>

HIDDEN is a TYPE attribute value to the INPUT element for forms. It indicates a form field that does not appear visibly in the document and that the user does not interact with. It can be used to transmit stale information about the client or server. Hidden fields can be viewed via the Page Source. Therefore, it's unadvisable to put passwords in a hidden field.

Selects

Selects present a list of options to the user. You can specify whether a user can select only one or many items from the list. The <select> element defines a select list. Each item on the list is specified with the option element. The syntax is:

<select name="name"> <option>Label of Option</option> </select>

Additionally, there are several attributes that can be set within <select>:

  • The name attribute is required and specifies how to access the data after form submission.

  • The size attribute specifies how many lines of the list appear in the browser window. The default is a drop-down list.

  • The multiple attributes allow the user to select more than one item from the list.

There are two commonly used attributes for <option>:

  • The selected attribute specifies a default selection.

  • The value attribute specifies a value that is different from the label of the option. If no value is specified, the label of the option is used as the value.

A selection list that doesn't have multiple attributes can have only one option selected by default.


A common use for a select list is providing options from which a user may choose, such as that created in Figure.

Multiple book types

<form>
<select name="media" multiple="multiple">
  <option></option>
  <option>Hard Cover</option>
  <option>Soft Cover</option>
  <option>Reference</option>
  <option>Audio Books</option>
</select>
</form>

Figure shows the list built from the code in Figure.

Multiple items selected from the list


The first option in the list is actually a blank entry. This is useful for detecting if a user hasn't made any changes to a list.

Working with Multiple Values

Having checkboxes and radio buttons creates a new problem. You can't use a single value when processing the results of a group of checkboxes with the same name or elements from a select list. Figure shows an example.

A form with checkboxes using the same name to store multiple values

<html>
<head>
<title>Using Default Checkbox Values</title>
</head>
<body>
<?php
$food = $_GET["food"];
if (!empty($food)){
echo "The foods selected are: <strong>";
foreach($food as $foodstuff){
echo '<br />'.$foodstuff;
}
echo "</strong>.";
}
else {
echo ('
<form action="'.$_SERVER["PHP_SELF"].'" method="GET">
<fieldset>
<label>
Italian
<input type="checkbox" name="food[]" value="Italian" />
</label>
<label>
Mexican
<input type="checkbox" name="food[]" value="Mexican" />
</label>
<label>
Chinese
<input type="checkbox" name="food[]" value="Chinese" checked="checked" />
</label>
</fieldset>
<input type="submit" value="Go!" />');
}
?>
</body>
</html>

Figure produces something like Figure.

The Chinese checkbox is checked by default


You gave the user the choice of three different ethnic foods: Italian, Mexican, and Chinese. In this example, the user can check multiple checkboxes. Therefore, you need to access more than a single value from the name of the checkbox when you process the form submission in PHP. We'll place a pair of brackets ([]) after the field's name attribute to send the results in an array.

In the following code, the name attribute is set to food[] instead of food. Without the array, if a user checks multiple foods, his selections would be overwritten by the last food checked in the list. Placing closed brackets after the input name signifies an array. Since you want to have one choice checked already, give it an attribute of checked, and then set it to checked. This sets the checkbox to be set by default in a user's browser.

<html>
<head>
  <title>Using Default Checkbox Values</title>
</head>
<body>
<?php
$food=$_GET[food];
$self=$_SERVER['PHP_SELF'];
if (!empty($food))
{
  echo "The foods selected are:<br />";
  foreach($_GET[food] as $foodstuf)
  {
   echo "<strong>$foodstuf</strong><br />";
  }
}
else
{
  echo ("<form action=\"$self\" ");
  echo ('method="get">
   <fieldset>
    <label>Italian <input type="checkbox" name="food[]" value="Italian" /></label>
    <label>Mexican <input type="checkbox" name="food[]" value="Mexican" /></label>
    <label>Chinese <input type="checkbox" name="food[]" value="Chinese"
checked="checked" /></label>
   </fieldset>
    <input type="submit" value="Go!" >
        ');
}
?>
</body>
</html>

If you select two checkboxes, you'll see the screen in Figure.

Selecting Italian and Chinese


The screen in Figure produces the screen in Figure, when submitted.

Each check field is displayed


You can set up radio buttons in the same way, but name should be set to food instead of food[], since radio buttons tell users they have only one choice.

Lastly, notice in the preceding code that the checkboxes are wrapped around a fieldset tag. This is used to logically define a set of data.

Validating Data

Whenever you are taking data from a user, you should always validate it. If you do not validate the user's input, it can cause many problemsmost importantly, substantial security risks.

Validating input is not complicated. We'll go over the most common PHP functions that are used to sanitize data from users.

Validating checkboxes, radio buttons, and selects

Validating data that comes from checkboxes, radio buttons, or selects is easier than validating free format fields such as text boxes, because the value should only be one of the predefined values. To ensure this, store all of the options in an array and make sure the user input is part of the array when you process the data. We'll look at the code for checking input from a single selection (in other words, only one checkbox, radio button, or other selection), as shown in Figure.

Checking input from a radio button or a single select

<?php
$options = array('option 1', 'option 2', 'option 3');
// Coming from a checkbox or a multiple select statement
$valid = true;
if (is_array($_GET['input'])) {
$valid = true;
foreach($_GET['input'] as $input) {
if (!in_array($input, $options)) {
$valid = false;
}
}
if ($valid) {
// process input
}
}
?>

Validating text boxes and text areas

To validate text boxes and text areas, you first need to gather what information is valid and what isn't. Also, you don't want to allow the user to enter nothing. You can spend as little time as checking to see whether a string is empty, or you can build more complex expressions to check for the presence of certain characters, such as the @ in an email address. You can use the code in Figure to make sure the input is acceptable.

Checking input from a checkbox or a multiple select

<?php
    $options = array('option 1', 'option 2', 'option 3');

    //coming from a checkbox or a multiple select statement
    $valid = true;
    if (is_array($_GET['input'])) {
      $valid = true;
      foreach($_GET['input'] as $input) {
        if (!in_array($input, $options)) {
          $valid = false;
        }
      }
      if ($valid) {
        //process input
      }
    }
?>

Since we haven't given you much tangible, sink-your-teeth-into-it PHP code, we're going to give you a great example of how PHP can easily create a conversion tool. Using conversion tools, you could convert from Fahrenheit to Celsius, or U.S. Units of Measurement to Metric. Pretty cool, huh?

Building a Feet-to-Meters Converter in PHP

We're going to show you the power of PHP by creating a feet-to-meters converter application, shown in Figure, which would be handy if your web site is used internationally.

PHP feet-to-meters converter

<head>
<title>Feet to meters conversion</title>
</head>
<body>
<?php
// Check to see if the form has been submitted
$feet = $_GET["feet"];
if ($_GET[feet] != NULL){
echo "<strong>$feet</strong> feet converts to <strong>";
echo $feet * 0.3048;
echo "</strong> meters.<br />";
}
?>
<form action="<?php echo($_SERVER['PHP_SELF']); ?>" method="GET">
<label>Feet:
<input type="text" name="feet" value="<?php echo $feet; ?>" />
</label>
<input type="submit" value="Convert!" />
</form>
</body>
</html>

This self-processing form collects a measurement in feet, multiplies that measurement by a standard conversion factor, and then prints out the results. Since you still have the original value for feet in the $feet variable from the form submission, you use it as an initial value when displaying the Feet user input field in the form. Figure shows the results of entering 12 and clicking Convert.

Simply convert feet to meters using a mathematical formula


Building a Time Zone Conversion Utility in PHP

Now that you've learned how to do a variety of tasks, let's put it all together to get an idea of what can be done in PHP. Figure uses forms, arrays, conditionals, looping, and date strings. These all work together to bring you a handy tool for converting between some common time zones.

Converting between time zones based on user input

 1 <html>
 2 <head>
 3 <title>Time Zone Converter</title>
 4 </head>
 5 <body>
 6 <?php
 7 // An array holds the standard time zone strings
 8 $time_zones = array("Asia/Hong_Kong",
 9 "Africa/Cairo",
 10 "Europe/Paris",
 11 "Europe/Madrid",
 12 "Europe/London",
 13 "Asia/Tokyo",
 14 "America/New_York",
 15 "America/Los_Angeles",
 16 "America/Chicago");
 17 // Check to see if the form has been submitted
 18 if ($_GET["start_time"] != NULL){
 19 $start_time_input = $_GET["start_time"];
 20 $start_tz = $_GET["start_tz"];
 21 $end_tz = $_GET["end_tz"];
 22 putenv("TZ=$start_tz");
 23 $start_time = strtotime($start_time_input);
 24 echo "<p><strong>";
 25 echo date("h:i:sA",$start_time)."\n";
 26 echo "</strong>";
 27 putenv("TZ=$end_tz");
 28
 29 echo "in $start_tz becomes ";
 30 echo "<strong> ";
 31 echo date("h:i:sA",$start_time)."\n";
 32 echo "</strong>";
 33 echo " in $end_tz.</p><hr />";
 34 }
 35 ?>
 36 <form action="<?php echo($_SERVER['PHP_SELF']); ?>" method="GET">
 37 <label>
 38 Your Time:
 39 <input type="text" name="start_time" value="<?php echo $start_time_input; ?>" />
 40 </label> in
 41 <select name="start_tz">
 42 <?php
 43 foreach ($time_zones as $tz) {
 44 echo '<option';
 45 if (strcmp($tz, $start_tz) == 0){
 46 echo ' selected="selected"';
 47 }
 48 echo ">$tz</option>";
 49 }
 50 ?>
 51 </select>
 52 <p>Convert to:
 53 <select name="end_tz">
 54 <?php
 55 foreach ($time_zones as $tz) {
 56 echo '<option';
 57 if (strcmp($tz, $end_tz) == 0){
 58 echo ' selected="selected"';
 59 }
 60 echo ">$tz</option>";
 61 }
 62
 63 ?>
 64 </select>
 65 <input type="submit" value="Convert!">
 66 </form>
 67 </body>
 68
 69 </html>

Here's what happened in Figure on a line-by-line basis:

  • Lines 9 through 17 populate an array with a handful of time zones from around the world.

  • Line 20 checks to see whether there is a value for the $start_time. It's assumed that if there's a value, then the code has been launched in response to the user submitting the form.

  • Line 25 sets the environmental variable that defines the current time zone. PHP uses this for both the strtotime and date functions.

  • Line 42 begins building the user input form. We'll give the user the chance to make another time comparison.

  • Lines 43 through 49 and 55 through 61 loop through the time zones in the array. They also check whether the passed-in value from the form submission matches a time zone value. If it does, insert the selected attribute so that the time zone settings are remembered from the last form submission.

Figure show an example of converting the time from Chicago to Paris.

Converting Chicago time to Paris time


Querying the Database with Form Data

Once you've validated your data, you're ready to start using information from the forms in your database queries. Figure creates a function called query_db from the code in Chapter 7 for displaying authors with a change to line 11 that allows matching the title with a LIKE search clause. LIKE and NOT LIKE are usually used with strings and possibly with wildcards, such as the underscore (_) and the percentage sign (%).

  • The underscore (_) matches a single character.

  • The percent sign (%) matches zero or more characters.

In Figure, the function takes a single parameter and searches for the specific book title you're looking to find.

Combining form processing and database querying

 1 ?php
 2 function query_db($qstring) {
 3 include('db_login.php');
 4 require_once('DB.php');
 5 $connection = DB::connect("mysql://$db_username:$db_password@$db_host/$db_database");
 6
 7 if (DB::isError($connection)){
 8 die ("Could not connect to the database: <br />". DB::errorMessage($connection));
 9 }
 10 $query = "SELECT * FROM `books` NATURAL JOIN `authors`
 11 WHERE `books`.`title` like '%$qstring%'";
 12 $result = $connection->query($query);
 13 if (DB::isError($result)){
 14 die("Could not query the database:<br />".
 15 $query." ".DB::errorMessage($result));
 16 }
 17 echo ('<table border="1">');
 18 echo "<tr><th>Title</th><th>Author</th><th>Pages</th></tr>";
 19 while ($result_row = $result->fetchRow()) {
 20 echo "<tr><td>";
 21 echo $result_row[1] . '</td><td>';
 22 echo $result_row[4] . '</td><td>';
 23 echo $result_row[2] . '</td></tr>';
 24 }
 25 echo ("</table>");
 26 $connection->disconnect();
 27 }
 28 ?>
 29 <html>
 30 <head>
 31 <title>Building a Form</title>
 32 </head>
 33 <body>
 34 <?php
 35 $search = $_GET["search"];
 36 $self = $_SERVER['PHP_SELF'];
 37 if ($search != NULL){
 38 echo "The search string is: <strong>$search</strong>.";
 39 query_db($search);
 40 }
 41 else {
 42 echo ('
 43 <form action="'.$self.'" method="get">
 44 <label>Search:
 45 <input type="text" name="search" id="search" />
 46 </label>
 47 <input type="submit" value="Go!" />
 48 </form>
 49 ');
 50 }
 51
 52 ?>
 53 </body>
 54 </html>

Line 50 completes the processing of the form data. The search string is sent to the query_db function. This example shows a fairly simple search done by searching a words table, and then outputting the results on the pages that are being used, as shown in Figure.

We see our familiar text box for searching


Searching for "ing" matches one title, shown in Figure.

The book titles that contain "ing" are displayed


Shortening up the search string to in outputs an additional title, as shown in Figure.

Shortening the search string gives more results


While this code works pretty well, it's starting to get more complicated and intricate than some people are comfortable with. The solution is to break out the HTML from the PHP.



 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows