A function that builds an HTML select list from any mysql table
function html_drop_down ($in_name ,$in_tablename ,$in_value_column_name ,$in_display_column_name ,$in_other_value = "" ,$in_other_display = "" ,$in_selected_value = "" ,$in_where_clause = "") { // build the SQL string $sql = "SELECT " . $in_value_column_name . " col_val," . $in_display_column_name . " col_disp" . " FROM " . $in_tablename; if ($in_where_clause) { $sql .= " " . $in_where_clause; } $sql .= " order by col_disp"; // connect to mysql, put your specifics here. mysql_pconnect() or die ("problems connecting to Database."); // queries the database, be sure to name your database. $result = mysql_db_query("ecomm",$sql); // build the select list. if ($result) { $return_value = ""; } else { $return_value .= "No data."; } mysql_free_result($result); return $return_value; } ?>
/* Here's three examples of how you can use this function */ /* Simple example */ echo html_drop_down ("formvar1_prod_type" ,"prod_types" ,"prod_type_id" ,"name"); /* An example with an extra value in the list, good for N/A, All values for queries etc.. */ echo html_drop_down ("formvar2_prod_type" ,"prod_types" ,"prod_type_id" ,"name" ,"-1" ,"All Types"); /* An example with a where clause */ echo html_drop_down ("formvar3_prod_type" ,"prod_types" ,"prod_type_id" ,"name" ,"-1" ,"All Types" ,"3" ,"WHERE prod_type_id <> 4"); /* Here's the data used in my example, it should work with any table though: mysql> select prod_type_id, name from prod_types; +--------------+-------------------+ | prod_type_id | name | +--------------+-------------------+ | 1 | Mother Boards | | 2 | Graphics Cards | | 3 | Memory | | 4 | Pointing Devices | | 5 | Keyboards | | 6 | Operating Systems | +--------------+-------------------+ 6 rows in set (0.00 sec) mysql> */ ?>