Input select generated from query – PHP
Just a handy function that I use a lot.
With this function you can generate an input select from a given query.
Parameters:
1- Query to be displayed as a select, the query needs to returns at least 2 values, 1st one for the option value, and the 2nd one for the display value.
2-Input Select name, thisw woud be the name that your select will have in the form.
3-Which option it’s selected from the list. I non is set the first one it’s selected.
function sqlOption($sql,$name,$option){//generates a select tag with the values specified on the sql, 2nd parameter name for the combo, , 3rd value selected if there's global $ocdb; $result =$ocdb->query($sql);//1 value needs to be the ID, second the Name, if there's more doens't work $sqloption= "<select name='".$name."' id='".$name."'> <option value='0'>Home</option>"; while ($row=mysql_fetch_assoc($result)) { $first=mysql_field_name($result, 0); $second=mysql_field_name($result, 1); if ($option==$row[$first]) { $sel="selected=selected";} $sqloption=$sqloption . "<option ".$sel." value='".$row[$first]."'>" .$row[$second]. "</option>"; $sel=""; } $sqloption=$sqloption . "</select>"; echo $sqloption; }
Same function but that can group:
Parameters:
1- Query to be displayed as a select, the query needs to returns at least 2 values, 1st one for the option value, the 2nd one for the display value, and 3rd the value we use to group with.
2-Input Select name, thisw woud be the name that your select will have in the form.
3-Which option it’s selected from the list. I non is set the first one it’s selected.
function sqlOptionGroup($sql,$name,$option){//generates a select tag with the values specified on the sql, 2nd parameter name for the combo, , 3rd value selected if there's global $ocdb; $result =$ocdb->query($sql);//1 value needs to be the ID, second the Name, 3rd is the group //echo $sql; $sqloption= "<select name='".$name."' id='".$name."' onChange=\"validateNumber(this);\" lang=false ><option></option>"; $lastLabel = ""; while ($row=mysql_fetch_assoc($result)) { $first=mysql_field_name($result, 0); $second=mysql_field_name($result, 1); $third= mysql_field_name($result,2); if($lastLabel!=$row[$third]){ if($lastLabel!=""){ $sqloption.="</optgroup>"; } $sqloption.="<optgroup label='$row[$third]'>"; $lastLabel = $row[$third]; } if ($option==$row[$first]) { $sel="selected=selected";} $sqloption=$sqloption . "<option ".$sel." value='".$row[$first]."'>" .$row[$second]. "</option>"; $sel=""; } $sqloption.="</optgroup>"; $sqloption=$sqloption . "</select>"; echo $sqloption; }
NOTE: Requires phpMyDB.
Does this still work with the latest version of phpMyDB?
Thanks
Steve
Webmaster of dewaltbatteries.org
yes it works ;)