Pages

Wednesday, May 25, 2011

PHP dynamic navigation

Here is the code for dynamic nested navigation system.

Step1: Need to create a data base table " dyn_menu "
------------------------------------------------------------
CREATE TABLE `dyn_menu` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `label` VARCHAR(50) NOT NULL DEFAULT '',
  `parent_id` INT(11) NOT NULL DEFAULT '0',
  PRIMARY KEY  (`id`)
) TYPE=MyISAM;

------------------------------------------------------------

Step2: PHP script to generate menu system

------------------------------------------------------------

$sel = "select * from dyn_menu";
$res = mysql_query($sel);
while($dat = mysql_fetch_assoc($res))
{
    if($dat["parent_id"] == 0)
    {
        $parent_array[$dat["id"]]["label"] = $dat["label"];
    }
    else
    {
        $sub_array[$dat["id"]]["label"] = $dat["label"];
        $sub_array[$dat["id"]]["parent"] = $dat["parent_id"];
        $parent_array[$dat["parent_id"]]["count"]++;
    }
}




foreach($parent_array as $pkey => $pval)
{
    echo "<ul>";
    if(!isset($pval["count"]))
    {
        echo "<li>". $pval["label"] ."</li>";
    }
 else
    {  
     echo "<li>". $pval["label"] ."</li>";
        echo "<ul>";
       
        foreach($sub_array as $skey => $sval)
        {
            if($sval["parent"] == $pkey)
            {
                echo "<li>". $sval["label"] ."</li>";
            }
        }       
        echo "</ul>";
    }
    echo "</ul>";
}


-----------------------------------------------------

** I think it will help you, this is an example for level-1 sub menu system . For increasing menu level put the php script in recursive function and make necessary changes.

3 comments:

  1. hey expert i got a problem when launching XAMPP in
    my browser like this;
    "Unable to open wamp servers manager please check the path in index.php"

    can you solve it..??

    ReplyDelete
  2. Please make sure you are closed all other web services (IIS...)...

    ReplyDelete