/ Published in: PHP
This is one of my favs to use and reuse. Essentially, we make a select box on what is in the table filled values/labels.
Download the ISO countries list to make a country table and Bam! with this function you got a country select box... Also great for foreign keys...
Other Examples:
auto\_maker, auto\_maker\_id
color\_name, color\_id
Download the ISO countries list to make a country table and Bam! with this function you got a country select box... Also great for foreign keys...
Other Examples:
auto\_maker, auto\_maker\_id
color\_name, color\_id
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
// FUNCTION getSelectFromTable // // Make a select box based on value and labels in a table. // // $name -> the name of the form element // $table -> the table to base off of // $labels -> Which field has the labels: Ford, GM, Fiat // $values -> field has the values: 1,37,99 // $where -> option where clause that you can put in // $orderby -> default ordering is on the label field but you can override // $default -> What should the first option be if needed. // array x['label'] = "Make a Choice" x['value'] = "" // leave blank for blank... function getSelectFromTable( $name , $table , $labels , $values , $where = -1 , $orderby = -1 , $default = null ) { // if we have a where clause use it if not nevermind if( $where == -1 || $where == null ) { $where = ""; } else { $where = " WHERE ".$where; } // if we have an order by use it other wise order by label field if( $orderby == -1 || $orderby == null ) { $orderby = " ORDER BY ".$labels." ASC"; } else { $orderby = " ORDER BY ".$orderby; } $temp = ""; // get the labels and the values from the table $q = "SELECT ".$labels." as label, ".$values." as value FROM ".$table."".$where.$orderby; $qr = dbquery( $q ); // begin building the select box // you can css on the #id if you want $temp .= "<select class=\"form_element\" name=\"".$name."\" id=\"".$name."\">"; // build the first option if this is null then we just a get a blank // one $temp .= "<option value=\"".$default['value']."\">".$default['label']."</option>\n"; // roll through the result set building the options while( ! $qr->EOF ) { $temp .= "<option value=\"".$qr->fields['value']."\""; // lets make this one selected if it was selected before if( $_POST[$name] == $qr->fields['value'] ) { $temp .= " selected"; } // sorry for the entities and such but when you live // amongst french speaking folks they tend be anal about // their precious special charecters théy rêà lly suck còck! $qr->MoveNext(); } $temp .= "</select>\n"; return $temp; }