You are here: Home » All Posts » PHP Form » Handling select box (drop-down list) in a PHP form

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

in 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 “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

Be Sociable, Share!
costin stoica July 12, 2011 at 11:48 am

Very useful your post. Thank you. I have succesfully used the second method.

Technomixx.com July 14, 2011 at 2:16 pm

Thanks for sharing nice information … if there is any way to change the selected option using javascript then please share ..

Chardar July 14, 2011 at 2:17 pm

Yes I am also interested solve this problem using JS..

Joseph Innocent July 15, 2011 at 7:24 pm

I need urgent help!
I need the codes for inserting the value of a dropdown menu based on a radio button selection into a mysql table. The radio button select will alter the menu items of the dropdown.

nurulhusna September 12, 2011 at 6:53 am

i want select only current year..what coding should i use???
for example
year:box(in box can choose waht year i want)

Imran Haider November 24, 2011 at 9:24 pm

reply me i will tell you how you can use year in listbox.

Eamonn Kenny September 23, 2011 at 11:16 am

Shockingly you are the only person I’ve found on the internet who has a full working example like this (using google search, that is). I’ve been able to implement your technique perfectly for a very complicated dashboard. Thanks.
even w3schools explanation of how to use the multiple select is rubbish, because they don’t explain how to manipulate the form data that is obtained in the array. So, in fact their examples are unusable. Also, you are the only person I’ve seen to include the array [ ] inside the name. I don’t see how the multiple values are collectable without this, meaning that most other web examples are incomplete.

Stephen Sanders October 2, 2011 at 10:27 pm

This post gave me a sense of a how a PHP form is made. Its great that there are resources such as this which exist and are helpful to those who are developing and creating their own websites.

Marut October 13, 2011 at 2:54 pm

Fine article,its very useful for me

Thanks

PolicyWala October 20, 2011 at 4:12 pm

Useful article. Thanks

Daily News October 23, 2011 at 5:07 am

good but i want fetch selected user name
like that select * from table name where name = xyz

souleye November 16, 2011 at 11:33 pm

hi thank you for the post. I downloaded the two files but they happen to be the exact same. I tried to use it on my wordpress contact page but it’s not working. it’s not seeing the select part, nor is it seeing the validation. I’m trying to solve this issue for future projects. thanks.

Mohammed Abdul Moiz November 22, 2011 at 3:37 am

i have following codes…

Room Type *

Select Room

Grand Room

Junior Suite

Executive Suite

Royal Suites

now i want to show price of the particular room on the selection from drop down…
please help me….

Electricians West London December 9, 2011 at 9:35 am

Hello, I€™m new to php and I have my first task, there is already an existing program but what I need to revise is a drop down, for example when the user select registered, the next text box will be enable for the input of registration NO. If I chose as not registered then the textbox will be disabled. Any Ideas?
West London Electricians

samon December 13, 2011 at 11:23 am

hi please tell me how to return a list from a list means
if we have a list x which displays name .if we choose any of name it displays further information in list form in another given combo

Karen December 19, 2011 at 1:45 pm

Thank you for this tutorial. It was really helpful and following it got me exactly what I needed.

I think it would be helpful (especially for unexperienced programmers) if you also included the code for the submit-button :)

ravi January 7, 2012 at 10:57 am

Nice forum for php tuts.

Dinesh January 19, 2012 at 8:17 am

And how to fetch data from database on the form like same….?

Deepakraj February 23, 2012 at 4:41 pm

This is for easy select box

select ID
<?php

$con=mysql_connect("localhost","root","");
mysql_select_db("sky",$con);
$result=mysql_query("select name from salary",$con);
echo "”;
while($row=mysql_fetch_array($result))
{
$id=$row['name'];
echo “”.$id.”";

}
echo “”;
?>

passioncoder March 6, 2012 at 5:17 am

Hi,
Your example was very useful….
But after getting the values from the php form,i am trying to store the values in the database….
But the loop exits after executing once…ie..Only one value is inserted into the table….
Kindly help me out for this…..
[CODE]
$teacherid = $_GET['stuid'];
$aCountries = $_POST['level_select'];
if(!isset($aCountries))
{
echo(“You didn’t select any levels!\n”);
}
else
{
$nCountries = count($aCountries);
echo(“You selected $nCountries countries: “);
for($i=0; $i get_record_sql(“INSERT INTO {teacher_level} VALUES (‘$teacherid’,$aCountries[$i])”);
}
echo(“”);
[/CODE]

passioncoder March 6, 2012 at 8:17 am

hey its working fine….now got to delete records of the same id…

Comments on this entry are closed.

Previous post:

Next post: