html form guide
  about

Using select box in a PHP form

This tutorial will show you how to add select boxes and multi-select boxes to a form, how to retrieve the input data from them, how to validate the data, and how to take different actions depending on the input.

Select box

Let's look at 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 "formSex" value when accessed by PHP will be "M".

<p>
  What is your sex?
  <select name="formSex">
    <option value="">Select...</option>
    <option value="M">Male</option>
    <option value="F">Female</option>
  </select>
</p>

The selected value from this input was can be read with the standard $_POST array just like a text input and validated to make sure the user selected Male or Female.

<?php
  if($_POST['formSubmit'] == "Submit") {
    $varMovie = $_POST['formMovie'];
    $varName = $_POST['formName'];
    $varSex = $_POST['formSex'];
    $errorMessage = "";

    // - - - snip - - -
  }
?>

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.

<?php
  if($varSex == "") {
    $errorMessage .= "<li>You forgot to select your sex!</li>";
  }
?>

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

Multi-select

Suppose you want to present a select box that allows the user to select multiple options. Here is how to create such an input in HTML:

<p>What countries have you visited?</p>
<select multiple="multiple" name="formCountries[]">
  <option value="US">United States</option>
  <option value="UK">United Kingdom</option>
  <option value="France">France</option>
  <option value="Mexico">Mexico</option>
  <option value="Russia">Russia</option>
  <option value="Japan">Japan</option>
</select>

Note the similarity to a checkbox group. First, set multiple="multiple" as a property of the select box. Second, put [] at the end of the name. Finally, we don't really need a "blank" option in this select box, because we can simply check to make sure the user selected something or not. To select multiple values, use the shift or ctrl buttons when clicking.

The PHP code to process this field is very similar to the checkbox code. $_POST['formCountries'] returns an array of the selected values.

<?php
if($_POST['formSubmit'] != "") {
  $aCountries = $_POST['formCountries'];
 
  if(is_null($aCountries)) {
    echo("<p>You didn't select any countries!</p>\n");
  } else {
    echo("<p>You selected countries: ");
    for($i=0; $i < count($aCountries); $i++)
    {
      echo($aCountries[$i] . " ");
    }
    echo("</p>");
  }
}
?>

As before, use "is_null" to make sure some values were selected.

Using switch

Now let's change the multi-select box back to a standard single select box. We want to now perform different actions based on what selection the user makes. You could write a bunch of "if" statements, but that could get messy. Let's look at two ways: dynamic commands and the switch statement.

<?php
if($_POST['formSubmit'] != "") {
  $varCountry = $_POST['formCountry'];
  $errorMessage = "";

  if($errorMessage != "") {
    echo("<p>There was an error with your form:</p>\n");
    echo("<ul>" . $errorMessage . "</ul>\n");
  } else {
    // method 1: switch
    switch($varCountry)
    {
      case "US": header("Location: US.html"); break;
      case "UK": header("Location: UK.html"); break;
      case "France": header("Location: France.html"); break;
      case "Mexico": header("Location: Mexico.html"); break;
      case "Russia": header("Location: Russia.html"); break;
      case "Japan": header("Location: Japan.html"); break;
      default: echo("Error!"); exit(); break;
    }
   
    // method 2: dynamic redirect
    header("Location: " . $varCountry . ".html");
    exit();
  }
}
?>

These two approaches have their pro's and con's. The switch method is basically a concise method of writing a bunch of "if" statements. Each case matches the variable passed the switch and performs all actions after that case up until a break statement. In this case, each case is redirecting to the corresponding page to the selected country. If the selected country is not found in one of the cases, the "default" case is assumed, and "Error!" is displayed.

The second method is just passing the selected value to the header function to redirect to the correct page.

The first method requires writing more code, but is more secure because it ensures the form only redirects to 6 pre-programmed cases, or else displays an error message and ends execution.

The second method is much more concise, but less secure because a malicious user could monkey around with the form and submit whatever value he wants. If using method 2, it's a good idea to validate the selected country first, to make sure it won't result in a redirect to a malicious page.

Download the php form select sample 1 and download the php form select sample 2.

  • Digg
  • del.icio.us
  • Netscape
  • Reddit
  • StumbleUpon
  • Technorati
  • YahooMyWeb

Related pages

 
  • Digg
  • del.icio.us
  • Netscape
  • Reddit
  • StumbleUpon
  • Technorati
  • YahooMyWeb
Email forms
  How to get email from html form submission

Email form using 'mailto'

Form to email using PHP

Email form with file attachment in PHP

Form mail scripts
  Form mail script selection guide

Perl based form mail

Contact Forms
  PHP based email contact form

Secure your HTML contact form using captcha
PHP Form
  PHP form validation script

PHP form tutorial: first steps

PHP form processing

PHP form 'GET'

PHP form 'POST'

Handling checkbox in PHP form processor

Handling select box in a PHP form

Using PHP_SELF in the action field of a form

How to submit a form using PHP

Creating a registration form using PHP

Making a login form using PHP

Creating a multi-page order form using PHP

Passing PHP form variables from one page to other

  Copyright © 2008 html-form-guide.com . All rights reserved.