Building dynamic form dropdowns using PHP

This can be very simple, if you know what you are doing.
First off, I like to make mine into a function but you can do whatever you would like with it.

Lets get started. First we need to echo out the starting tag for a dropdown form. Then we're going to add an 'default' listing to the dropdown so that we have something to look at when it first loads, instead of usernames. I find this is quite better then looking at the first user in the A's. It's all up to you.

CODE
echo "<select name="userList" id="userList">";
echo "<option value="none" selected="selected">-Select User-</option>";




Next we're going to get the SQL going.

CODE
        $query = mysql_query("SELECT * FROM `members` ORDER BY `uid` ASC")or die( mysql_error() );


This here is where we select * (* = wildcard) from the `members` table and order it by the `uid` and then ASC.


Next is the loop using the SQL query.

CODE
        while( $r = mysql_fetch_array( $sql ) )
            {
            echo "<option value="".$r['id']."">".$r['name']."</option>";
            }


This code just takes the SQL and extracts the information needed to be displayed and then loops the whole `members` table out.


Now we have to close our dropdown tag.

CODE
echo "</select>";




And your finished! Wasn't quite that hard eh. Finally here is our full code.


CODE
<?php
echo "<select name="userList" id="userList">";
echo 
"<option value="none" selected="selected">-Select User-</option>";

        
$query mysql_query("SELECT * FROM `members` ORDER BY `uid` ASC")or die( mysql_error() );
        while( 
$r mysql_fetch_array$sql ) )
            {
            echo 
"<option value="".$r['id']."">".$r['name']."</option>";
            }

echo 
"</select>";
?>

Friday September 14, 2007 - 790 reads