PHP: Create a HTML drop down/select box from a database

January 28, 2010 – 11:22 am

Here is a function I use all of the time. It takes the contents of a mySQL table and creates an HTML select box (I call them drop downs) from it.

 
# $table: The mySQL table to use.
# $column: The column in $table to display
# $name: The HTML name of the drop down
# $selected: The value that the drop down defaults to.
# $show_any: If you have a row in the table where the $column equals
                    00_Any it will be displayed.
#                  This is useful for having an Any or All value.
# $distinct: Only show DISTINCT() $column
function dropdown_db($table, $column, $name, $selected,
                              $show_any = 1, $distinct = 0) { 
 
  $dropdown = "
<select id=\"$name\" name=\"$name\">\n"; 
 
  $any_sql = '';
  if(!$show_any) {
    $any_sql = " WHERE $column <> '00_Any' ";
  } 
 
  $select = $column;
  if($distinct) {
    $select = "DISTINCT($column)";
  } 
 
  $from_db = "SELECT $select FROM $table $any_sql ORDER by $column";
  $from_db2 = mysql_query($from_db) ;
  while($from_db3=mysql_fetch_array($from_db2, MYSQL_ASSOC)) { 
 
    $value = $from_db3["$column"]; 
 
    $pretty_db = $value;
    $pretty_db = str_replace('00_', '', $pretty_db);
    $pretty_db = str_replace('_', ' ', $pretty_db); 
 
    $SELECTED = '';
    if($value == $selected) {
        $SELECTED = ' SELECTED';
    } 
 
    $dropdown .= "
<option value=\"$value\"$SELECTED>$pretty_db</option>
 
\n";
  } 
 
  $dropdown .= "</select>
 
\n"; 
 
  return($dropdown);
}
 

Post a Comment



thevedic.net

Part of the thevedic.net.
[Contact Me] - [Mud Emporium] - [Ozark, AR] - [See my Port?]

This site is in no way represents the opinions or positions of any company or organization including those who employ the creators of this web site. We're not responsible for the content, posts, responses by other users or ideas of any sites that are linked to on this page. This site is recommended for ages 18 and up.

VEDIC VEKO IS PROSPEROUS

Arkie Imports | Dean Vaughan | Dean Vaughan | K. Dean Vaughan | Kenneth Vaughan | Pig Trail 23 | Pig Trail Pics | See My Port Forward Info | See My Port Forward Info


I'm not affiliated with the following in anyway.
Arkansas MMA - Inferno Mixed Martial Arts - Inferno Martial Arts Club - Inferno Martial Arts Club - Official Inferno Fight Gear - Inferno Fight Equipment - Inferno Combat Gear - IFC Online - Inferno Fight Gear - Inferno MMA - Inferno Fight Gear