I want to create a hierarchical menu. The function:
/*
* Table has 3 fields: `ID`, `PARENTID` and `NAME`
* `ID` is unique, `PARENTID` showing his parent node id.
* This function will go through it and build unordered list and call itself when needed to build subitems.
* $level argument used to define wich node's subitems to build. Default is 0 which is top level.
*/
function showMenu($level = 0) {
$result = mysql_query("SELECT * FROM `menus` WHERE `submenu` = ".$level);
echo "<ul>";
while ($node = mysql_fetch_array($result)) {
echo "<li>".$node['name'];
$hasChild = mysql_fetch_array(mysql_query("SELECT * FROM `menus` WHERE `submenu` = ".$node['id'])) != null;
IF ($hasChild) {
showMenu($node['id']);
}
echo "</li>";
}
echo "</ul>";
}
I've found on a stackoverflow in a similar question.
I have a table menus
:
+----+----------------+---------+
| id | name | submenu |
+----+----------------+---------+
| 1 | FIRST HEADER | NULL |
| 2 | SECOND HEADER | NULL |
| 3 | THIRD HEADER | NULL |
| 4 | (fh) submenu 1 | 1 |
| 5 | (fh) submenu 2 | 1 |
| 6 | (fh) submenu 3 | 1 |
| 7 | (sh) submenu 1 | 2 |
| 8 | (sh) submenu 2 | 2 |
| 9 | (th) submenu 1 | 3 |
| 10 | item 1 | 4 |
| 11 | item 2 | 4 |
+----+----------------+---------+
I used this function in script
showMenu(4);
and here is the result:
<ul><li>item 1</li><li>item 2</li></ul>
as u can see, there is no word about even a piece of hierarchy, just a couple of items in source. What possibly wrong in my code?
You are specifically requesting just the submenu number 4
.
If you just call showMenu()
with no arguments, it will show the entire menu tree.