dumdumsareyum Posted August 7, 2008 Share Posted August 7, 2008 I wrote a little function to make a selection list of all the distinct values in a mysql database column. You can also send a value that you would like to be pre-selected should it match one of the generated list items. I'm sure it's nothing new, but I sure do like it so I thought I'd post it and maybe someone else would find it useful too. Here's an example of how to use the function: Select Location(s): <br /> <select name="location[]" multiple ="multiple" size="3"> <option value="" selected="selected">All Locations</option> <?php /*****Get locations from database****/ createSelection("location", $cxn, "propertyData"); ?> </select> And here is the function: function createSelection($columnName, $cxn, $table, $match) { //$columnName is the column name of in the table you wish to create a selection list from (gets distinct values from this col only) //$cxn is a mysqli connection //$table is the table you wish to retreive values from //$match is a value that you wish to be selected in the selection list if it matches any of the values in the created list $sql = "SELECT Distinct $columnName from $table order by $columnName"; $result = mysqli_query($cxn, $sql) or die(DPP_error("There was an error processing your request. Please try again")); while ($row = mysqli_fetch_assoc($result)) { if ($row[$columnName] != "") { echo "<option value='".$row[$columnName]."'"; if(($row[$columnName] == $match) && ($match != "")) { echo " selected='selected'"; } echo ">".$row[$columnName].PHP_EOL; } } } //end function I thought about including the selection tags and a parameter for the name attribute etc., but I think it's pretty flexible this way and still gets the job done. Link to comment https://forums.phpfreaks.com/topic/118545-function-im-proud-of/ Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.