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 changed mysql> 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.
<?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>'.print_r($countries,true));
That will terminate 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 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>
<option>England, London</option>
<option>France, Paris</option>
<option>Italy, Rome</option>
<option>Malaysia, Kuala Lumpur</option>
<option>New Zealand, Wellington</option>
<option>United States, Washington D.C.</option>
</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>\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=\"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.