HTML.form.guide

Handling select box (drop-down list) in a PHP form

drop-down list PHP php form select

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 “formGender” value when accessed by PHP will be “M”.


<p>
What is your Gender?
<select name="formGender">
  <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(isset($_POST['formSubmit']) )
{
  $varMovie = $_POST['formMovie'];
  $varName = $_POST['formName'];
  $varGender = $_POST['formGender'];
  $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(!isset($_POST['formGender'])) 
{
  $errorMessage .= "<li>You forgot to select your Gender!</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:


<label for='formCountries[]'>Select the countries that you have visited:</label><br>
<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>

Please 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(isset($_POST['formSubmit'])) 
{
  $aCountries = $_POST['formCountries'];
  
  if(!isset($aCountries)) 
  {
    echo("<p>You didn't select any countries!</p>\n");
  } 
  else 
  {
    $nCountries = count($aCountries);
    
    echo("<p>You selected $nCountries countries: ");
    for($i=0; $i < $nCountries; $i++)
    {
      echo($aCountries[$i] . " ");
    }
    echo("</p>");
  }
}

?>

As before, use “isset” is 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(isset($_POST['formSubmit'])) 
{
  $varCountry = $_POST['formCountry'];
  $errorMessage = "";
  
  if(empty($varCountry)) 
  {
    $errorMessage = "<li>You forgot to select a country!</li>";
  }
  
  if($errorMessage != "") 
  {
    echo("<p>There was an error with your form:</p>\n");
    echo("<ul>" . $errorMessage . "</ul>\n");
  } 
  else 
  {
    // note that both methods can't be demonstrated at the same time
    // comment out the method you don't want to demonstrate

    // method 1: switch
    $redir = "US.html";
    switch($varCountry)
    {
      case "US": $redir = "US.html"; break;
      case "UK": $redir = "UK.html"; break;
      case "France": $redir = "France.html"; break;
      case "Mexico": $redir = "Mexico.html"; break;
      case "Russia": $redir = "Russia.html"; break;
      case "Japan": $redir = "Japan.html"; break;
      default: echo("Error!"); exit(); break;
    }
    echo " redirecting to: $redir ";
    
    // header("Location: $redir");
    // end method 1
    
    // method 2: dynamic redirect
    //header("Location: " . $varCountry . ".html");
    // end method 2

    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 Sample Code

Download the PHP form select samples below:

php-form-select-1.zip

php-form-select-2.zip

See Also