PHP: Create a HTML drop down/select box from a database
January 28, 2010 – 11:22 amHere 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);
}
