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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
edawson003
Forum Contributor
Posts: 133
Joined: Thu Aug 20, 2009 6:34 am
Location: Los Angeles, CA - USA

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

Post 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>';
 ?>
User avatar
dude81
Forum Regular
Posts: 509
Joined: Mon Aug 29, 2005 6:26 am
Location: Pearls City

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

Post 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>';
 
User avatar
edawson003
Forum Contributor
Posts: 133
Joined: Thu Aug 20, 2009 6:34 am
Location: Los Angeles, CA - USA

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

Post by edawson003 »

Works great! Thanks! :D
Post Reply