Recently I've written recursive PHP function which generates website navigation based on parent-child structure like this
<ul>
<li>parent
<li>child</li>
</li>
</ul>
Code looks like that
function generateMenu($parent, $level, $db){
$q = $db->query("select id, name FROM menu WHERE parent = '$parent'");
if($level > 0 && $q->num_rows > 0) echo "\n<ul>\n";
while($row=$q->fetch_object()){
echo "<li>";
echo '<a href="?page=' .$page. '">' . $row->name . '</a>';
//display this level's children
generateMenu($row->id, $level++, $menu, $db);
echo "</li>\n\n";
}
if($level > 0 && $q->num_rows > 0) echo "</ul>\n";
}
The piece of code above simply echoes <ul><li> structure (like given above example) from db table.
Now the questions is, how to create navigation menu like on this website?
Please take a look at left sidebar.
http://www.smithsdetection.com/continuous_vapour_sampling.php
Now i think that:
- First of all we need to echo all parents
- Function must get current pages id as an input value (for ex. $current)
- Function must echo til' current pages level
I can't figure out how to modify my function, to get output like on given website. PLease help.
BTW
My db table looks like that

NOTE Please don't post answers about sql injection holes, I've already taken care about them: checking with in_array (if variable listed in column names array) and passing through real_escape.
generateMenu($row->id, $level++, $menu, $db);should probably begenerateMenu($row->id, $level+1, $menu, $db);.$levelafter it is incremented, too. Consider when$level = 0:if($level > 0 && $q->num_rows > 0) echo "\n<ul>\n";will NOT output an opening<ul>, then latergenerateMenu($row->id, $level++, $menu, $db);increments$levelto 1 so that after your while loop,if($level > 0 && $q->num_rows > 0) echo "</ul>\n";WILL output a closing</ul>, which is not matched to any opening one. Check your HTML that gets returned to see.$level = 0, when you callgenerateMenu($row->id, $level++, $menu, $db)$levelactually gets incremented after you pass it to the function, so the function always sees$level = 0. Compare:$level++with++$level, and read the manual link you posted above.