Hey guys, I'm trying to wrap my head around this problem. I have a horizontal menu that is dynamically created from a MySQL database. Getting it to display the menu items at the top-level is easy, but I was wondering what exactly I need to do to get it to display any submenu items that match the parent's id? I'm having trouble sorting out the pseudo code on paper that will allow this to work.
My main purpose is to have an easy way to add/edit main menu items and/or submenu items on the backend without having people delve into the actual website code. All of that logic has pretty much been coded already though, what I really am stuck on is displaying menus and the corresponding menu's sub menus.
Here is my database schema for the navigation...
CREATE TABLE `nav_menu_main` (
`menu_id` tinyint(5) unsigned NOT NULL auto_increment,
`menu_text` varchar(50) NOT NULL,
`menu_url` varchar(50) NOT NULL,
`menu_active` tinyint(1) unsigned NOT NULL,
`menu_is_editable` tinyint(1) unsigned NOT NULL,
`menu_pos` tinyint(5) unsigned NOT NULL,
PRIMARY KEY (`menu_id`))
CREATE TABLE `nav_menu_submenu` (
`sub_menu_id` tinyint(5) unsigned NOT NULL auto_increment,
`menu_id` tinyint(5) unsigned NOT NULL,
`sub_menu_text` varchar(50) NOT NULL,
`sub_menu_url` varchar(50) NOT NULL,
`sub_menu_active` tinyint(1) unsigned NOT NULL,
`sub_menu_external` tinyint(1) unsigned NOT NULL,
`sub_menu_pos` tinyint(5) unsigned NOT NULL,
PRIMARY KEY (`sub_menu_id`))
Here's the code I use to get the main navigation items out of the database into an unordered list.
<?php
$query = "SELECT menu_id, menu_text, menu_url, menu_pos
FROM nav_menu_main
WHERE menu_active = 1
ORDER BY menu_pos";
// Run the query
if (!($result = mysql_query($query, $conn)))
die("***Error running query:" . mysql_error());
while ($row = mysql_fetch_assoc($result))
{
$menu_id = $row["menu_id"];
$menu_text = $row["menu_text"];
$menu_url = $row["menu_url"];
//$pageid is set somewhere else in the page's code
if ($pageid == $menu_id){
$style = " class=\"active\"";
}else{
$style = "";
}
echo "\t\t<li><a href=\"" . $menu_url . "\"" . $style . ">" . $menu_text . "</a></li>\n";
}
?>
How do I make it so that when a menu contains children it will nest them under the correct parent?
For example:
<div id="nav">
<ul>
<li><a href="/">Home</a></li>
<!--This parent item contains a child-->
<li><a href="/schedule/">Schedule</a>
<ul>
<li>2007 Schedule of Events</li>
</ul>
</li>
<li><a href="/results/">Race Results</a></li>
<li><a href="/points/">Points Standings</a></li>
<li><a href="/gallery/">Photo Gallery</a></li>
<li><a href="/visitors/">Visitors</a></li>
<li><a href="/contact/">Contact Us</a></li>
<li><a href="/forums/">Forums</a></li>
</ul>
</div>
I hope I was clear enough in what I am trying to accomplish. Any help would be greatly appreciated.