Help with PHP recursive navigation list menu
- by Jason
Hi all,
I am trying to add a dynamic recursive navigation list menu to a site of am working on.
The scenerio is that the menu has 2 levels related by a parentid(preid).
My issue is that I can display the 1st level list correctly, however I cannot get the second level to display properly. I am not sure where to add the UL and /UL tags for the second level.
This is what I am after
<ul>
<li>Item 1</li>
<li>item 2</li>
<li>item 3</li>
<ul>
<li>sub item 1</li>
<li>sub item 2</li>
</ul>
<li>Item 4</li>
<li>item 5</li>
<ul>
<li>sub item 1</li>
<li>sub item 2</li>
</ul>
<li>item 6</li>
</ul>
This is actually what i am getting with the below code:
<ul>
<li>item 1
<ul>
</ul>
</li>
<li>item 2
<ul>
<li>sub item 1</li>
<ul>
</ul>
<li>sub item 2</li>
<ul>
</ul>
</ul>
</li>
<li>Sports Injuries
<ul>
</ul>
</li>
</ul>
</li>
</ul>
Below is the class file I am using to create the menu:
class Dynamic_Menu
{
function getConfig()
{
$this->DB_SERVER = 'localhost';
$this->DB_USER = '***';
$this->DB_PASS = '***';
$this->DB_NAME = '***';
}
function __construct()
{
$this->getConfig();
$Conn = mysql_connect($this->DB_SERVER, $this->DB_USER, $this->DB_PASS);
if (!$Conn)
die("Error: ".mysql_errno($Conn).":- ".mysql_error($Conn));
$DB_select = mysql_select_db($this->DB_NAME, $Conn);
if (!$DB_select)
die("Error: ".mysql_errno($Conn).":- ".mysql_error($Conn));
}
function select_row($sql)
{
//echo $sql . "<br />";
if ($sql!="")
{
$result = mysql_query($sql) or die("Error: ".mysql_errno().":- ".mysql_error());
if ($result)
{
while($row = mysql_fetch_array($result))
$data[] = $row;
}
return $data;
}
}
function recordCount($sql)
{
if ($sql!="")
{
$result = mysql_query($sql) or die("Error: ".mysql_errno().":- ".mysql_error());
if ($result)
{
$cnt = mysql_num_rows($result);
return $cnt;
}
}
}
function getChild($id)
{
$menu = "";
$str = "";
$s = "SELECT * FROM vcms_sys_explorer WHERE preid = '$id' ";
$res = $this->select_row($s);
$menu .= '<ul>';
for ($i=0;$i<count($res);$i++)
{
$cnt_of_child = $this->recordCount("SELECT * FROM vcms_sys_explorer where preid = '".$res[$i][eid]."' ");
//if ($cnt_of_child > 0)
// $str = '';
//else
// $str = " (is sub menu item)";
$menu .= '<li>'. $res[$i][name].$str.'</li>';
$menu .= $this->getChild($res[$i][eid]);
}
$menu .= '</ul>';
return $menu;
}
function getMenu($parentid)
{
$menu = "";
$s = "SELECT * FROM vcms_sys_explorer WHERE preid = '$parentid' ";
$res = $this->select_row($s);
$menu .= '<ul>';
for ($i=0;$i<count($res);$i++)
{
$menu .= '<li>'.$res[$i][name].$this->getChild($res[$i][eid]).'</li>';
if ((count($res) - 1) > $i) {
}
}
$menu .= '</ul>';
return $menu;
}
}
I call the menu with:
$menu = new Dynamic_Menu();
$menu->getMenu(1);
Could someone please help and explain where I need to place the level 2 UL and /UL tags. I have been banging my head with this for the last 2 days.
Any help would be greatly appreciated, thanks...