My db table looks like that. I'm trying to generate nav. menu from db table. Here is my tables screenshot
I wanna get something like that
<li><a href="?page=1">Level 1</a>
<ul>
<li><a href="?page=2">Level2</a>
<ul>
<li><a href="?page=3">Level3</a></li>
</ul>
</li>
</ul>
</li>
And here is my recursive php function that generates nav function.
<!doctype html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<?php
require 'core/includes/db.php';
function menu($parent, $level){
global $db;
$q = $db->query("select * from menu where parent = '$parent'");
if($level > 0 && $q->num_rows > 0){
echo '<ul>';
}
while($row=$q->fetch_object()){
echo "<li>".$q->name."</li>"; (line 14)
//display this level's children
menu($q->id, $level+1); (line 16)
}
if($level > 0 && $q->num_rows > 0){
echo '</ul>';
}
}
echo '<ul>' . menu(0,0) . '</ul>'
?>
Actually it doesn't generate anything. It works recursively and getting bunch of errors in php logs.
[15-Sep-2011 00:47:22] PHP Notice: Undefined property: mysqli_result::$id in E:\Web Server\smiths-heimann.az\nav.php on line 16
[15-Sep-2011 00:47:22] PHP Notice: Undefined property: mysqli_result::$name in E:\Web Server\smiths-heimann.az\nav.php on line 14
What's wrong with my function? Please help to fix that
UPDATE Final PHP CODE
<!doctype html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<?php
require 'core/includes/db.php';
function menu($parent, $level){
global $db;
$q = $db->query("select * from menu where parent = '$parent'");
if($level > 0 && $q->num_rows > 0){
echo '<ul>';
}
while($row=$q->fetch_object()){
echo "<li>";
echo '<a href="?page=' . $row->id . '">' . $row->name . '</a>';
//display this level's children
menu($row->id, $level+1);
echo "</li>\n";
}
if($level > 0 && $q->num_rows > 0){
echo '</ul>';
}
}
echo '<ul>' . menu(0,0) . '</ul>'
?>
</html>
OK. Now i'm getting what exactly what i want. Thank you Adam very much. But there are 3 pair of empty 's at the end of page. Why they are appearing? Please take a look
<!doctype html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<li><a href="?page=1">Ana Səhifə</a></li>
<li><a href="?page=2">Təftiş texnikası</a><ul><li><a href="?page=3">Təhlükə üzrə sıralanma</a></li>
</ul></li>
<li><a href="?page=4">Istifadə olunan texnologiyalar</a><ul><li><a href="?page=5">Qamma şüa spektroskopiyası</a></li>
<li><a href="?page=6">Portativ Ion Spektrometri</a></li>
<li><a href="?page=7">İnfra qırmızı</a></li>
<li><a href="?page=8">Mikrodalğa</a></li>
<li><a href="?page=9">Raman Spektroskopiyası</a></li>
<li><a href="?page=10">Rentgen araşdırma sistemləri</a><ul><li><a href="?page=11">Məktub və Banderolların yoxlanışı</a></li>
<li><a href="?page=12">HiTraX Texnologiyası</a></li>
</ul></li>
</ul></li>
<ul></ul>
</html>