Create a gist now

Instantly share code, notes, and snippets.

Populate select elements with PHP / MySQL
<?php
// example sql statement
$sql = "SELECT col_for_value, col_for_label FROM some_table";
function database_select($tbl_value, $tbl_label, $select_name, $label, $init_val = "") {
global $sql;
$result = mysql_query($sql);
$menu = "<label for=\"".$select_name."\">".$label."</label>\n";
$menu .= "<select name=\"".$select_name."\">\n";
$curr_val = (isset($_REQUEST[$select_name])) ? $_REQUEST[$select_name] : $init_val;
$menu .= ($curr_val == "") ? " <option value=\"\" selected>...\n" : "<option value=\"\">...\n";
while ($obj = mysql_fetch_object($result)) {
$menu .= " <option value=\"".$obj->$tbl_value."\"";
$menu .= ($obj->$tbl_value == $curr_val) ? " selected" : "";
$menu .= ">".$obj->$tbl_label."\n";
}
$menu .= "</select>\n";
mysql_free_result($result);
return $menu;
}
// example:
// use the col names from the table too...
echo database_select("col_for_value", "col_for_label", "my_select", "Select from:");
/* example output
<label for="my_select">Select from:</label>
<select name="my_select">
<option value="" selected>...
<option value="val_1">value 1
<option value="val_2">value 2
...
</select>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment