This is really a very basic and very simple method of populating a select box with database data. For example, If you have a list of states in your database, you could create a drop-down box that you can select all the states without a long drawn out piece of code. Here’s what your table entitled ’states’ MIGHT look like
StateID (Primary Key)
Abbr
Name
This table simply includes an auto incrementing key, the state abbreviation and the state name. Now here is your code to create the drop-down!
<?php
### CREATE DATABASE LINK ###
$hostname=’localhost’;
$username=’username’;
$password=’password’;
$dbname=’databasename’;
mysql_connect($hostname, $username, $password) or die(mysql_error()) ;
mysql_select_db($dbname) or die(mysql_error()) ;### FUNCTION ###
function getStateSelectBox() {
$SQLstate = “SELECT * FROM `states` ORDER BY state ASC”;
$results = mysql_query($SQLstate);
$output = “<select name=\”state\”>\n”;
while ($rows = mysql_fetch_array($results)) {
$output .= “ <option name=\”$rows[1]\”>$rows[2]</option>\n”;
}
$output .= “</select>”;
return $output;
}### DISPLAY OUTPUT ###
$stateselectbox = getGenreSelectBox();
echo $stateselectbox;
?>
This can be used for nearly any site or drop-down if its database driven. Note the “\n” at the end of some of the $output variables because in case you didn’t know, this forces a lie break so its cleans up the look of the HTML. Its not needed, but nice if you prefer some form of sanity to your HTML output.An example of the output html code would be like this with this formatting, otherwise it would all be in one continuous line:
<select name=”state”>
<option name=”IA”>Iowa</option>
<option name=”NE”>Nebraska</option>
etc….
</select>
I hope you find this useful…I know its very simple, but its beneficial to know.







