Following on from the previous post is this tutorial. This one is very similar except this time we’re going to do the same trick with some radio buttons. The same principles as last time apply – we’ll read the values we want into an array and then use foreach to echo them out.
Radio buttons aren’t too much different to select boxes. Only one of the options in the group can be chosen, and only one can be preselected. Since we’ve already established the basics in the dropdown tutorial, we’ll just jump in boots and all and start rendering our output. The HTML output is slightly different – radio buttons have no containing element as the select does – they’re bound together by having a common name element.
<input type="radio" name="country" value="1"> New Zealand, Wellington<br /><input type="radio" name="country" value="2"> Australia, Canberra<br /><input type="radio" name="country" value="3"> England, London<br /><input type="radio" name="country" value="4"> United States, Washington D.C.<br /><input type="radio" name="country" value="5"> France, Paris<br /><input type="radio" name="country" value="6"> Italy, Rome<br /><input type="radio" name="country" value="7"> Malaysia, Kuala Lumpur<br />
And that displays in your browser like so:
New Zealand, Wellington
Australia, Canberra
England, London
United States, Washington D.C.
France, Paris
Italy, Rome
Malaysia, Kuala Lumpur
Regarding preselecting an option, we do the same thing as we did in the dropdown by testing the ID value of the current array element ($c) with the value of the ID passed into the script ($_GET['id']).
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:
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 (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:
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:
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:
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:
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.
It’s snowing. It’s the first snow of the year even – not bad considering we’ve made it all the way into June withouth a flurry thus far. We all went out to my parents’ place for tea tonight and on the way back we were turned around at the bottom of Three Mile Hill as the road was closed. I said to Linda that it was probably precautionary rather than reactive.
But as we got home we had trouble getting up Brockville Rd due to ice and snow. We ended up leaving the car about a block away and trudging the rest of the way in the bitter cold wind leaving footprints in the snow.
I’m just sitting here hoping some lunatic isn’t going to crash into our car while it’s parked! There were some nutters out slaloming up the hill in their rear-wheel drive kidsmobile. Kind of cool to watch but they almost hit one parked car on the side of the road.