Skip to content

Instantly share code, notes, and snippets.

@finalwebsites
Created March 29, 2016 06:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save finalwebsites/f63b61a717210927ffd4 to your computer and use it in GitHub Desktop.
Save finalwebsites/f63b61a717210927ffd4 to your computer and use it in GitHub Desktop.
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