Skip to content
All gists
Back to GitHub
Sign in
Sign up
Sign in
Sign up
{{ message }}
Instantly share code, notes, and snippets.
finalwebsites
/
populate-select-menu-mysql.php
Created
March 29, 2016 06:07
Star
0
Fork
0
Star
Code
Revisions
1
Embed
What would you like to do?
Embed
Embed this gist in your website.
Share
Copy sharable link for this gist.
Clone via HTTPS
Clone with Git or checkout with SVN using the repository’s web address.
Learn more about clone URLs
Download ZIP
Populate select elements with PHP / MySQL
Raw
populate-select-menu-mysql.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Show hidden characters
<?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
You can’t perform that action at this time.
You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.