PHP: Creating a drop down selection box

This post is the first of what will hopefully be many. It was inspired by a request for help from a friend so I figured why not go to down and document the whole process. In this post you will learn how to build a drop down selection box in HTML using PHP.

Fortunately it’s pretty simple, but it’s easy to trip up on the data structures involved. So long as you take it slowly and use debugging techniques (listed below) to help you understand what’s going on, you should be OK.

First of all, I’m going to create a new mySQL table to hold some sample data.

mysql> use test;Database changedmysql> create table countries (          id int not null auto_increment primary key,           country varchar(80),           capital varchar(80));Query OK, 0 rows affected (0.05 sec)

Now I’m going to create some sample data to work with:

INSERT INTO `countries` (`id`, `country`, `capital`) VALUES (1,'New Zealand','Wellington'),(2,'Australia','Canberra'),(3,'England','London'),(4,'United States','Washington D.C.'),(5,'France','Paris'),(6,'Italy','Rome'),(7,'Malaysia','Kuala Lumpur');

And now finally I’ll do a SELECT to ensure that it’s all in there properly (plus it looks nicer to see it in this format than in the INSERT format above)

mysql> select * from countries;+----+---------------+-----------------+| id | country       | capital         |+----+---------------+-----------------+| 1  | New Zealand   | Wellington      || 2  | Australia     | Canberra        || 3  | England       | London          || 4  | United States | Washington D.C. || 5  | France        | Paris           || 6  | Italy         | Rome            || 7  | Malaysia      | Kuala Lumpur    |+----+---------------+-----------------+7 rows in set (0.00 sec)

Excellent. Now we have some data to play with. Regardless of where your data is actually stored (it could be in a text file, the results of a POSTed form or elsewhere) the easiest way to work with it (in my opinion) is to load it into an array first. Let’s start our PHP script. The full thing is available at the bottom of this post.

&lt?php  // Connect to the test datbase on localhost  // That's where we created the countries table above  mysql_connect('localhost','username','password');  mysql_select_db('test');

  // Query the countries table and load all of the records  // into an array.  $sql = 'SELECT * FROM countries';  $res = mysql_query($sql) or die(mysql_error());  while ($rec = mysql_fetch_assoc($res)) $countries[] = $rec;?>

Ok, now what we have is the contents of our countries table in an array called $countries. Here’s where it’s useful to be able to debug that array to see what’s actually in it. At the end of your script, add a line that says this:

  die('<pre&gt'.print_r($countries,true));

That will terminate (die) the script, and print out the contents of the $countries array in readable form. We prepend the output with a <pre> for readability. When you run this script (by pointing your web browser at it), you should see the following:

Array(    [0] => Array        (            [id] => 1            [country] => New Zealand            [capital] => Wellington        )

    [1] => Array        (            [id] => 2            [country] => Australia            [capital] => Canberra        )

and so on. This is great, it shows that the $countries array is loaded with the details that we entered into the database. You can use this anywhere you want to see the current value of a variable. This is the quickest way of seeing what’s going on, short of having access to a sophisticated PHP debugger.

Now comes the fun part – this is where we build the select box. A select box is represented in HTML by a <SELECT> tag, with multiple <OPTION> tags inside it. These OPTION tags build up the list of selectable values. One of those OPTION tags can have a SELECTED attribute to determine which of the OPTION tags is the visibly selected option. We’ll cover the SELECTED attribute later, but our first aim is to get the $countries array displaying as a drop down box.

What we want our script to output is HTML that looks like this:

  <SELECT name="dropdown">    <OPTION>Australia, Canberra</OPTION&gt    <OPTION>England, London</OPTION&gt    <OPTION>France, Paris</OPTION&gt    <OPTION>Italy, Rome</OPTION&gt    <OPTION>Malaysia, Kuala Lumpur</OPTION&gt    <OPTION>New Zealand, Wellington</OPTION&gt    <OPTION>United States, Washington D.C.</OPTION&gt  </SELECT>

By using the foreach operator in PHP, we can easily iterate through all of the members in the $countries array. The above can be done with the following code:

  echo '<SELECT name="dropdown">';  foreach ($countries as $c)    echo "<OPTION>{$c['country']}, {$c['capital']}</OPTION&gt\n";  echo '</SELECT>';

It’s as simple as that. When you view this script in your browser you will see a dropdown box that looks just like this:

There are two more things that I want to do to this script now to make it more usable. The first is to include the ID of the countries in the OPTION tags and the second is to make it preselect a value based on input into the script. It is no easier to use the ID of the country than the name, but the advantage is that if the name of the country changes, or any spelling mistakes are corrected, then the ID will always remain the same. Data integrity is much stronger as well, although that is outside the scope of this tutorial.

Adding the ID into the OPTION tags is as simple as replacing our line above with this:

    echo "<OPTION value="{$c[id]}" >{$c['country']}, {$c['capital']}</OPTION&gt\n";

The drop down list still looks the same, but when the form it is in is posted (it’s not inside a form in this example), the value is posted instead of the visible text. Now we’ll draw the drop down box again, but we’ll preselect one of the options in it. We’ll check the value of $_GET['id'], which can be passed in from the URL (eg. dropdown.php?id=2).

To do this, all we do is check each member in the array as we echo it out, and if the ID of the country matches the ID passed in, then we’ll echo out the OPTION, but we’ll echo out a selected option instead of a regular unselected one.

  echo '<SELECT name="dropdown">';  foreach ($countries as $c)  {    if ($c['id'] == $_GET['id'])      echo "<OPTION value=\"{$c['id']}\" SELECTED>{$c['country']}, {$c['capital']}</OPTION>\n";    else      echo "<OPTION value=\"{$c['id']}\">{$c['country']}, {$c['capital']}</OPTION>\n";  }  echo '</SELECT>';

Now, if we run our script again, and pass in id=4 on the URL (i.e. dropdown.php?id=4), the output of the script will look like this:

  <SELECT name="dropdown">    <OPTION value="1">Australia, Canberra</OPTION>    <OPTION value="2">England, London</OPTION>    <OPTION value="3">France, Paris</OPTION>    <OPTION value="4" SELECTED>Italy, Rome</OPTION>    <OPTION value="5">Malaysia, Kuala Lumpur</OPTION>    <OPTION value="6">New Zealand, Wellington</OPTION>    <OPTION value="7">United States, Washington D.C.</OPTION>  </SELECT>

That’s it, we’re done. The full source code for this example is available here. Save it on your web server and point your web browser at it.

22 Comments

  • By Code Nexus, June 19, 2006 @ 10:56 am

    Nice tutorial. Do more please! I particularly like your style of coding and this helped solve a problem I’ve been having for quite some time. Almost solved I should say. After a bit of hacking I got it done though.

    I also had to hack your if statements condition. for some reason it didn’t check the string value on one side of the == with the one on the other side of it. It could have been how I was calling those bits of information or the data type in the database.

    To get it to work for me what I ended up with was something like.

    $theid = $_GET['id'];

    foreach ($countries as $c)
    {
    $chkselect = $c['id'];
    if ($chkselect == $theid)

    Again very nice tutorial and more would be great! :-)

  • By Michael Miller, June 21, 2006 @ 5:48 am

    Good effort Guru Bob. I know how long it takes to write tutorials like this one. Esp. with a real job as well.

  • By Anonymous, June 27, 2006 @ 5:15 pm

    thank you for the explination. If you have a moment… can you tell me how you would take the id from the value the user selected and send it to a php program?

    Kevin

  • By Guru, June 27, 2006 @ 9:04 pm

    Hi Kevin – as with any HTML form, any input elements that are inside the <FORM></FORM> definition are posted back to the server when the form is submitted.

    So, if you take the above example and wrap it in <FORM SRC=”myscript.php”>…</FORM> then the myscript.php form will receive the values posted from the HTML form.

    Take a look at the Getting Started section on the PHP web site for more examples.

  • By Anonymous, July 15, 2006 @ 2:00 am

    excellent script for dropdown ….thanks a lot:-)

  • By Anonymous, July 19, 2006 @ 6:07 am

    I am attempting to create two drop down boxes, one being dependant on the results of the other. When the user makes a selection from the first drop down a script (onChange) runs to refresh the page. During this refresh process is there any way to make the result available to the second drop down? There is no submit in between.

  • By Anonymous, July 19, 2006 @ 4:55 pm

    thanks guru bob…an excellent work there for the drop down menu..not much into OO..ur code is what i like yeahhh..

  • By Anonymous, August 7, 2006 @ 5:27 pm

    Thank you so very much!
    It explained the concepts so clearly and was very well written.
    This tutorial both helped me finish a project and gain a further understanding of PHP!

  • By Anonymous, September 26, 2006 @ 1:04 am

    You are simply Super :-) ))))

    by
    Sathiya

  • By Anonymous, December 2, 2006 @ 5:21 pm

    Hi. This may be a silly question: If I want to be able to select one of the ‘options’ (i.e. Auckland) and display all the fields of Auckland’s recordset (say Cafes, Tours, Weather ??) on another php page,(which means taking the url parameter)…how would I do that? I think I need some PHP to instruct the “action” field of the form to do all this,and also the options area should be a “repeating region” but I am still a beginner at PHP, and suspect I am making it too complicated. Look forward to your reply!
    Sandie

  • By Jehzeel Laurente, February 22, 2007 @ 1:13 pm

    It’s a very very very nice tutorial… Thank you so much! You deserved to be called a Guru :)

  • By Anonymous, July 5, 2007 @ 4:40 am

    Excellent Job, Keep it up.

  • By Anonymous, November 13, 2007 @ 5:30 pm

    I am trying to do a multiple selection of a dropdown list with checkboxes in it, using PHP. I need some pointers to get started. thanks.

  • By Anonymous, May 7, 2008 @ 3:32 am

    i have something i cannot get. I have multiple select dropdown box and i want to send multiple selection to a php program. please help me. this is what i have done so far…

    <br/>if (isset($_GET['multi'])) {
    $m=$_GET['multi'];
    echo $m;
    exit;
    }
    ?>
    <form method=”GET”> <SELECT name=”multi” multiple>
    <option value=”A”/>A
    <option value=”B”/>B
    <option value=”C”/>C
    </SELECT>
    <input type=”submit” value=”Submit” name=”submitform”>
    </FORM>

    if i select A & C and submit it i only get C.

  • By Guru, May 7, 2008 @ 2:13 pm

    Hi Anonymous,

    If you suffix the input name for the “multi” form elements with [] PHP will automatically convert the value to an array when it is posted.

    So, <select name=”multi[]” multiple=”multiple”> and then I would expect that your script will see that $_GET['multi'] is an array that look s like array(‘A’,'C’);

    By the way I’d suggest changing your form to a POST form just because your query string is going to start looking pretty ugly if you select heaps of value of long lengths, e.g. full country names. See how you go.

    Hope this helps.

  • By Steen, May 31, 2008 @ 1:03 am

    Hi Guru
    Thanks a lot for the turorial on how to create a drop down selection box – this was just what I needed.

  • By leahmarb, June 12, 2008 @ 9:24 pm

    This is a great tutorial. I was just wondering if it was possible to make several drop down lists that are dependant on each other change without having to reload the form?

  • By Mauricio Perez, June 13, 2008 @ 4:01 am

    oh mate…you really helped me with this! I’m so grateful…

    I’m working on this big project and I’ve had to learn to code…and this was very helpful!

    Thanks again!

  • By Anonymous, June 15, 2008 @ 9:27 pm

    i would like to ask the php coding to insert the selection into the database when admin ask us to state the others that not exist in the stated selection.

    sorry for my broken english.

  • By Anonymous, September 4, 2008 @ 1:20 am

    Thanks for the perfect tutorial. Just what I needed. Keep up the good work,
    Storm

  • By Anonymous, September 19, 2008 @ 4:22 am

    Hi,

    What about sending these option box selections to a database, along with text entered into a text area? how would I go about doing that?

    eg, a user enters text into a text area, chooses a option associated with the text they are entering, and both gets sent to a database, which can be retrieved later on, from another php web page or file…?

  • By רופא שיניים, January 29, 2011 @ 9:53 pm

    Hi !
    Nice post, thank you for putting up such an helpful and interesting information on your blog. I was looking for such blogs worldwide, to learn from, and came across your interseting blog. Please continue this great work and I look forward to more of your awesome blog posts.
    Thanks,
    Lilach.

Other Links to this Post

RSS feed for comments on this post. TrackBack URI

Leave a comment

WordPress Themes