Page 1 of 1

Attempting to set up a drop down menu that is tied to a sql

Posted: Sun Sep 20, 2009 5:15 pm
by edawson003
Attempting to set up a drop down menu that is tied to a sql table. I think I almost have all the components. Just can't figure out how to build the array based on optionid and optionname from my sql query. Want the optionname to show up in the drop down, but once a selection is made, I want the option id to post. Any takers? :)

Code: Select all

<?
    $optiondropdwnquery = "SELECT  optionid, optionname FROM OptionsLib WHERE optiongroupid = 1";   
    $optionsavailresult = mysql_query($optiondropdwnquery); 
    $options = array('15'=>'DisplayName1','19'=>'DisplayName2','24'=>'DisplayName3','28'=>'DisplayName4','50'=>'DisplayName5'); 
        $selectedValue = isset($_POST['foodtype']) ? $_POST['foodtype'] : '';
 echo '<select name="foodtype">' . "\n";
 foreach($options as $key=>$value) {
     echo '<option value="' . $key. '" ' . ($key== $selectedValue ? 'selected="selected"' : '') . '>' . $value . '</option>' . "\n";
 }
 echo '</select>';
 ?>

Re: Attempting to set up a drop down menu that is tied to a sql

Posted: Sun Sep 20, 2009 11:09 pm
by dude81
Assuming your query is right and getting the list of results properly, the below code should work

Code: Select all

 
 $optiondropdwnquery = "SELECT  optionid, optionname FROM OptionsLib WHERE optiongroupid = 1";  
 $optionsavailresult = mysql_query($optiondropdwnquery); 
 $selectedValue = isset($_POST['foodtype']) ? $_POST['foodtype'] : '';
 
  echo '<select name="foodtype">' . "\n";
while ($row = mysql_fetch_array($optionsavailresult, MYSQL_ASSOC)) {
     echo '<option value="' . $row['optionid']. '" ' . ($row['optionid']== $selectedValue ? 'selected="selected"' : '') . '>' .  $row['optionname'] . '</option>' . "\n";
}
 
  echo '</select>';
 

Re: Attempting to set up a drop down menu that is tied to a sql

Posted: Sun Sep 20, 2009 11:33 pm
by edawson003
Works great! Thanks! :D