PHP Forums Archive

Dynamic PHP menu

Tags: dynamic php, mysql menu

udaysingh79 posted on 2008-08-16 19:43:17 #

Hi Guys,

I have to create a dynamic menu using php and mysql. I have tried to used script given at this site at the following url: http://www.finalwebsites.com/tutorials/dynamic-navigation-list.php

I am able to get the first level of category menu but not able to get the second and any other level of menu. i think i am not able to get the CSS for this code, can somebody tell me what exactly the thing i am missing.

Comments / discussions

Olaf posted on 2008-08-17 16:50:22 #

Hi,

do you have an live example somewhere or paste the php code here.

Olaf posted on 2008-08-17 16:52:50 #

or better check the arrays, use this code before you call the function

print_r($sub_menu);

print_r($parent_menu);

udaysingh79 posted on 2008-08-18 18:31:33 #

Hi

here is the code i am using:

$link = mysql_connect('localhost','root','');
mysql_select_db('globalbiz',$link);

echo $sql = "SELECT id, cat_name, page_url, parent_id FROM test_cat ORDER BY parent_id, id ASC";
$items = mysql_query($sql);
while ($obj = mysql_fetch_object($items)) {
if ($obj->parent_id == 0) {
$parent_menu[$obj->id]['label'] = $obj->cat_name;
$parent_menu[$obj->id]['link'] = $obj->page_url;
} else {
$sub_menu[$obj->id]['parent'] = $obj->parent_id;
$sub_menu[$obj->id]['label'] = $obj->cat_name;
$sub_menu[$obj->id]['link'] = $obj->page_url;
$parent_menu[$obj->parent_id]['count']++;
}
}
mysql_free_result($items);

/////end first block
//echo"

"; print_r($sub_menu);exit;
///second block

function dyn_menu($parent_array, $sub_array, $qs_val = "menu", $main_id = "nav", $sub_id = "subnav", $extra_style = "foldout") {
    $menu = "<ul id=\"".$main_id."\">\n";
    foreach ($parent_array as $pkey => $pval) {
        if (!empty($pval['count'])) {
            $menu .= "
  • ".$pval['label']."
  • \n"; } else { $menu .= "
  • ".$pval['label']."
  • \n"; } if (!empty($_REQUEST[$qs_val])) { $menu .= "<ul id=\"".$sub_id."\">\n"; foreach ($sub_array as $sval) { if ($pkey == $_REQUEST[$qs_val] && $pkey == $sval['parent']) { $menu .= "
  • ".$sval['label']."
  • \n"; } } $menu .= "\n"; } } $menu .= "\n"; return $menu; } ////end second block if (!empty($_REQUEST[$qs_val])) { $menu .= "<ul id=\"".$sub_id."\">\n"; foreach ($sub_array as $sval) { if ($pkey == $_REQUEST[$qs_val] && $pkey == $sval['parent']) { $menu .= "
  • ".$sval['label']."
  • \n"; } } $menu .= "\n"; } function rebuild_link($link, $parent_var, $parent_val) { $link_parts = explode("?", $link); $base_var = "?".$parent_var."=".$parent_val; if (!empty($link_parts[1])) { $link_parts[1] = str_replace("&", "##", $link_parts[1]); $parts = explode("##", $link_parts[1]); $newParts = array(); foreach ($parts as $val) { $val_parts = explode("=", $val); if ($val_parts[0] != $parent_var) { array_push($newParts, $val); } } if (count($newParts) != 0) { $qs = "&".implode("&", $newParts); } return $link_parts[0].$base_var.$qs; } else { return $link_parts[0].$base_var; } } //// third block echo dyn_menu($parent_menu, $sub_menu, "menu", "nav", "subnav");

    Olaf posted on 2008-08-18 19:47:49 #

    Hi,

    do you tried the original code first?

    billybob777 posted on 2008-09-14 22:50:07 #

    Dear Olaf,

    I am having the same issue with the sub-menus. I have been trying to use the code that you have provided. In tracing through it, I believe it is in how I am marking the rows in the database. The arrays trace out based on feedback you have provided(see below), but I was wondering if you have a sample table of what the rows look like in MYSQL? Or is it maybe the CSS? Or does another column need an index? Any help would be great.

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    <link rel="nofollow" href="style/structure.css" rel="stylesheet" type="text/css" />
    
    </head>
    
    <body>
    
        <ul id="nav">
      <li><a class="foldout" rel="nofollow" href="test?menu=1">Design</a></li>
      <li><a class="foldout" rel="nofollow" href="where?menu=2">New Category</a></li>
    </ul>
    Array
    (
        [0] => Array
            (
                [parent] => 1
                [label] => Design
                [link] => design_link
            )
    
        [3] => Array
            (
                [parent] => 2
                [label] => New Category
                [link] => new
            )
    
        [4] => Array
            (
                [parent] => 2
                [label] => New Category
                [link] => new2
            )
    
    )
    Array
    (
        [1] => Array
            (
                [label] => Design
                [link] => test
                [count] => 1
            )
    
        [2] => Array
            (
                [label] => New Category
                [link] => where
                [count] => 2
            )
    
    )
    
    </body>
    </html>

    camdenite posted on 2009-07-16 12:18:42 #

    \Hi I'm confused, where is the css cod for this? I can get the parent menu but not the sub menu. What does $extra_style refer to?

    Cheers

    Olaf posted on 2009-07-16 12:29:15 #

    do you read the tutorial behind the link above?

    there is no stylesheet (not part of the tutorial)
    $extrastyle is just a variable that can hold a css pseudoclass

    "Note: sources at finalwebsites.com are for developer, it's (mostly) not ready-to-use code, but code which is easy to use if you know a little bit about PHP" ;)

    camdenite posted on 2009-07-16 16:13:27 #

    I know a little php but not loads - I did read the tutorial cheers :)

    Is it ok to ask for help on here?

    I can get the parent menu and the sub menu to appear but not mixed. And I am not sure why. The first line only shows the parent menu:

    echo dyn_menu($parent_menu, $sub_menu, "menu", "nav", "subnav");

    echo dyn_menu($parent_menu, "menu", "nav", "subnav");

    echo dyn_menu($sub_menu, "menu", "nav", "subnav");

    The others are parent_menu and sub_menu. I created a record sub of 1...

    Please advise -

    Cheers,
    Colin

    Olaf posted on 2009-07-16 16:52:09 #

    you need the function only ones, how does you array looks like ?(show it with print_r())

    camdenite posted on 2009-07-16 17:08:20 #

    Array ( [1] => Array ( [label] => Start [link] => # [count] => 1 ) [2] => Array ( [label] => Info [link] => http://www.yahoo.co.uk [count] => 2 ) ) Array ( [5] => Array ( [parent] => 1 [label] => About Us [link] => # ) [3] => Array ( [parent] => 2 [label] => fef [link] => http://www.google.co.uk ) [4] => Array ( [parent] => 2 [label] => efe [link] => # ) ) ArrayArray

    Cheers for looking :)

    camdenite posted on 2009-07-18 19:19:12 #

    OK not sure what is going on but I can see this post on this forum if I am logged in - but not if I'm not.

    I posted this - see below:

    Array ( [1] => Array ( [label] => Start [link] => # [count] => 1 ) [2] => Array ( [label] => Info [link] => http://www.yahoo.co.uk [count] => 2 ) ) Array ( [5] => Array ( [parent] => 1 [label] => About Us [link] => # ) [3] => Array ( [parent] => 2 [label] => fef [link] => http://www.google.co.uk ) [4] => Array ( [parent] => 2 [label] => efe [link] => # ) ) ArrayArray

    Olaf posted on 2009-07-19 09:01:38 #

    The post was marked as spam, could you post the array info between the code tags like

    echo 'hello World';

    This way it hard to read

    camdenite posted on 2009-07-19 09:06:15 #

    Ok I was wondering what was happening. Cheers for your help.

    Array (
       [1] => Array ( [label] => Start [link] => # [count] => 1 )
       [2] => Array ( [label] => Info [link] => http://www.yahoo.co.uk [count] => 2 ) )
        Array (
          [5] => Array ( [parent] => 1 [label] => About Us [link] => # )
          [3] => Array ( [parent] => 2 [label] => fef [link] => http://www.google.co.uk )
          [4] => Array ( [parent] => 2 [label] => efe [link] => # ) ) ArrayArray

    Olaf posted on 2009-07-19 18:49:52 #

    I guess this will not work, use the full code from the tutorial on your website, dump the array and send me the URL

    camdenite posted on 2009-07-19 21:48:20 #

    This is my code - adapted from above:

    <?php
    // Dynamic menu from http://www.finalwebsites.com/tutorials/dynamic-navigation-list.php
    
    // Connect to the db.
    require_once 'dyn_mysql_connect.php';
    
    $sql = "SELECT id, label, link_url, parent_id FROM dyn_menu ORDER BY parent_id, id ASC";
    $items = mysql_query($sql);
    while ($obj = mysql_fetch_object($items)) {
        if ($obj->parent_id == 0) {
            $parent_menu[$obj->id]['label'] = $obj->label;
            $parent_menu[$obj->id]['link'] = $obj->link_url;
        } else {
            $sub_menu[$obj->id]['parent'] = $obj->parent_id;
            $sub_menu[$obj->id]['label'] = $obj->label;
            $sub_menu[$obj->id]['link'] = $obj->link_url;
            $parent_menu[$obj->parent_id]['count']++;
        }
    }
    mysql_free_result($items);
    
    print_r($parent_menu);
    print_r($sub_menu);
    
    function dyn_menu($parent_array, $sub_array, $qs_val = "menu", $main_id = "nav", $sub_id = "subnav", $extra_style = "foldout") {
      $menu = "<ul id=\"".$main_id."\">\n";
      foreach ($parent_array as $pkey => $pval) {
          if (!empty($pval['count'])) {
              $menu .= "  <li><a class=\"".$extra_style."\" rel="nofollow" href=\"".$pval['link']."?".$qs_val."=".$pkey."\">".$pval['label']."</a></li>\n";
          } else {
              $menu .= "  <li><a rel="nofollow" href=\"".$pval['link']."\">".$pval['label']."</a></li>\n";
          }
          if (!empty($_REQUEST[$qs_val])) {
              $menu .= "<ul id=\"".$sub_id."\">\n";
    
              $menu .= "</ul>\n";
          }
      }
      $menu .= "</ul>\n";
      return $menu;
    }
    
    function rebuild_link($link, $parent_var, $parent_val) {
      $link_parts = explode("?", $link);
      $base_var = "?".$parent_var."=".$parent_val;
      if (!empty($link_parts[1])) {
          $link_parts[1] = str_replace("&amp;", "##", $link_parts[1]);
          $parts = explode("##", $link_parts[1]);
          $newParts = array();
          foreach ($parts as $val) {
              $val_parts = explode("=", $val);
              if ($val_parts[0] != $parent_var) {
                  array_push($newParts, $val);
              }
          }
          if (count($newParts) != 0) {
              $qs = "&amp;".implode("&amp;", $newParts);
          }
          return $link_parts[0].$base_var.$qs;
      } else {
          return $link_parts[0].$base_var;
      }
    }
    
    echo dyn_menu($parent_menu, $sub_menu, "menu", "nav", "subnav");
    echo dyn_menu($parent_menu, "menu", "nav", "subnav");
    echo dyn_menu($sub_menu, "menu", "nav", "subnav");
    ?>

    and my table sql

    CREATE TABLE IF NOT EXISTSdyn_menu` (
    id int(11) NOT NULL auto_increment,
    label varchar(50) NOT NULL default '',
    link_url varchar(100) NOT NULL default '#',
    parent_id int(11) NOT NULL default '0',
    PRIMARY KEY (id)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

    INSERT INTO dyn_menu (id, label, link_url, parent_id) VALUES
    (1, 'Start', '#', 0),
    (2, 'Info', 'http://www.yahoo.co.uk', 0),
    (3, 'fef', 'http://www.google.co.uk', 2),
    (4, 'efe', '#', 2),
    (5, 'About Us', '#', 1);`

    Cheers Olaf,

    Colin

    camdenite posted on 2009-07-19 21:51:46 #

    How come my posts don't show up unless I'm logged in? Am I still considered a spammer?

    Cheers

    Olaf posted on 2009-07-20 04:50:37 #

    looks like that the forum soft has some issues (need to upgrade very soon)

    It seems that you did everything alright, where is the link to your example page?

    camdenite posted on 2009-07-20 08:33:35 #

    All pages show just not mixed.

    Cheers.

    camdenite posted on 2009-07-20 08:41:15 #

    http://chocabloc.net/dyn_menu/dyn_menu.php

    Olaf posted on 2009-07-20 09:00:14 #

    as said before you need to call the function only ONES:

    echo dyn_menu($parent_menu, $sub_menu, "menu", "nav", "subnav");

    :)

    PS. maybe you can use a different email-address for your account (that should help akismet that you're not a spammer

    camdenite posted on 2009-07-20 10:24:17 #

    Yeah I remebered and did do that. I wanted to see that the submenu was returning as well - also just playing with the code. Thing is I wanted to get the parent and sub menus displaying together like:

    Parent
    - Child
    - Child
    Parent
    - Child
    - Child
    Parent
    - Child

    which echo dyn_menu($parent_menu, $sub_menu, "menu", "nav", "subnav"); looks like it should be doing.

    Baffled.

    Cheers,
    Colin

    camdenite posted on 2009-07-20 10:28:23 #

    Changed my email to my googlemail account. I think I am marked for life...

    camdenite posted on 2009-07-20 10:31:40 #

    With echo dyn_menu($parent_menu, $sub_menu, "menu", "nav", "subnav"); all I get is the parent_menu.

    Cheers.