Page 1 of 1

Dynamic dropdown menu with dynamic optgroup

Posted: Wed Dec 02, 2009 10:22 am
by MikeHynes
Hi all,

I'm putting together a database of Recipes according to cooking methods for a Boy Scout recipe page. Trying to create a simple dropdown menu using values pulled from MySQL database. I would like to have the menu segregated using <optgroup> for Cooking Methods (ie. Dutch Oven, Campfire, ets . . .) For the life of me I can not seem to get it to work.

Table structure for table mr_categories
Field Type Null Default
id int(10) No
catname varchar(200) No
comments text No
isParent enum('yes', 'no') No yes
childOf int(6) No 0
metaDesc text No
metaKeys text No
enComments enum('yes', 'no') No yes
enRecipes enum('yes', 'no') No yes
enRating enum('yes', 'no') No yes
enCat enum('yes', 'no') No yes

Table structure for table mr_recipes
Field Type Null Default
id int(10) No
name varchar(100) No
cat int(5) No 0
ingredients text No
instructions text No
submitted_by varchar(100) No
addDate date No 0000-00-00
hits int(7) No 0
metaDesc text No
metaKeys text No
enComments enum('yes', 'no') No yes
enRating enum('yes', 'no') No yes
enRecipe enum('yes', 'no') No yes
isApproved enum('yes', 'no') No no
comCount int(7) No 0
ratingCount int(8) No 0
ipAddresses text No
email varchar(250) No
rss_date varchar(35) No


PHP Code so far:

<select name="cb_meal">

<option value="">------------- Select Recipe ------------</option>

<?php
// Get and join records from database (table "mr_recipes & mr_categories")

$list = mysql_query("SELECT mr_recipes.cat, mr_categories.catname, mr_recipes.name, mr_recipes.id FROM mr_recipes INNER JOIN mr_categories ON mr_recipes.cat = mr_categories.id WHERE mr_categories.id='2' OR mr_categories.id='3' OR mr_categories.id='4' OR mr_categories.id='5' ORDER BY mr_categories.id ASC")
or die(mysql_error());

$result = mysql_query($list);

$group = array();

while ($row = mysql_fetch_assoc($result)){

$group[$row['catname']][] = $row;
}
foreach ($group as $key => $values)
{
echo '<optgroup label=" '. $key .' ">';
foreach ($values as $value)
{
?>

<option value="<?php echo $value['id']; ?>"><?php echo $value['name']; ?>
</option>

<?php
}
?>

</optgroup>

<?php
}
?>

</select>


As of now my SQL query returns this table


cat catname name id
2 Dutch Oven Apple Cobbler 3
2 Dutch Oven Test 9
3 Stove Top Simple Doughnuts 2
4 Campfire S'Mores 5
5 No Cook Chips (any flavor) 7


Any help would be greatly appreciated.

Thanks!