Search code examples
phpmenumysqlisubmenu

Output menu with submenu using php and mysqli


I'm trying to output an HTML menu and submenu with MySQLi and PHP.

My experience is not enough to solve this question.

Can I have some help?

I have the following table structure for pages:

CREATE TABLE `pages` (
  `id` int(100) NOT NULL AUTO_INCREMENT,
  `page_name` varchar(255) NOT NULL,
  `parent_id` int(100) NOT NULL,
  `link` varchar(255) NOT NULL,
  `target` varchar(255) NOT NULL,
  `enabled` int(1) NOT NULL DEFAULT '1',
  `sort` int(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;

The records:

INSERT INTO `pages` VALUES ('1', 'Home', '0', 'index.php', '_self', '1', '1');
INSERT INTO `pages` VALUES ('2', 'Team', '0', 'team.php', '_self', '1', '2');
INSERT INTO `pages` VALUES ('3', 'Posts', '0', 'posts.php', '_self', '1', '3');
INSERT INTO `pages` VALUES ('4', 'Programs', '0', 'programs.php', '_self', '1', '4');
INSERT INTO `pages` VALUES ('5', 'Program Name 1', '4', 'program1.php', '_self', '1', '1');
INSERT INTO `pages` VALUES ('6', 'Program Name 2', '4', 'program2.php', '_self', '1', '2');
INSERT INTO `pages` VALUES ('7', 'Program Name 3', '4', 'program3.php', '_self', '1', '3');
INSERT INTO `pages` VALUES ('8', 'Contact', '0', 'contact.php', '_self', '1', '8');

My objective is to output something like that:

Home
Team
Posts
Programs
--Program Name 1
--Program Name 2
--Program Name 3
Contact

Thanks


Solution

  • Im going to leave the details to yourself, but it will be something like this. Recursive is the keyword:

    function getMenu($parent=0, $depth=0){
        $menu = "<ul>"; // each section gets wrapped in UL
        // Select and query to get only the direct childs from $parent:
        $qItems = "SELECT id, page_name FROM pages WHERE parent=".$parent;
        $sItems = mysqli_query($conn, $qItems);
        // This will be the magic part:
        while($fItems = $sItems->fetch_assoc() ){
            $menu.= '<li>';
            $menu.= str_repeat('-', $depth).' '.$fItems['page_name'];
            $menu.= getMenu( $fItems['id'], $depth+1); // <- this is the magic! This will get the childs of this item
            $menu.= '</li>';
        }
    
        $menu.= "</ul>"; // each section gets wrapped in UL
        return $menu; // return it
    }
    
    echo getMenu(); // Do something with it :)
    

    I've added the $depth in this example so the dashes get place, to show how you can find your way into recursiveness
    Edit: Small but important note: This will go on endlessly if you keep adding childs to childs to ..., no need to update the code. That's one of the great powers of recursiveness