N-level menu using recursion

Recently I needed to come up with a code that would help me create a n-level menu and breadcrumb for that. So for that I wrote this code which works with great ease and provides huge flexibility. Also I kept it really low so that it is easy to embedded it in any kind of design. This is just the half part of my code which prints the menu.


$table	= 'menu';
function showMenu($ulclass, $liclass, $father) {
	$showmenu_query = "select * from $table where menu_father='" . $father . "' order by menu_order";
	$exec_showmenu = mysql_query($showmenu_query);

	if ( !$exec_showmenu) {
		echo "Query failed. Check your query.

Error Returned: " . mysql_error(); return false; } $toAppend = '
    '; while($row_showmenu=mysql_fetch_assoc($exec_showmenu)) { $toAppend.= '
  • '; $toAppend.= '' . stripslashes($row_showmenu['menu_name']); $toAppend.= ''; $submenu_query="select * from $table where menu_father='" . $row_showmenu['menu_id'] . "'"; $exec_submenu = mysql_query($submenu_query); if( mysql_num_rows($exec_submenu)>0 ) { $toAppend.= $showMenu($ulclass, $liclass, $row_showmenu['menu_id']); } $toAppend.= '
  • '; } $toAppend.= '
'; return $toAppend; }

Expected table structure:

 Table keys
 menu_id 		-> Primary key
 menu_name 		-> Menu name
 menu_class		-> Menu class
 menu_slug 		-> Menu link
 menu_order		-> Menu order
 menu_father 		-> Father menu id // For topmost level menu, menu_father needs to be 0

MYSQL Table structure

  `menu_id` int(11) NOT NULL AUTO_INCREMENT,
  `menu_name` varchar(256) NOT NULL,
  `menu_class` varchar(256) NOT NULL,
  `menu_slug` varchar(100) NOT NULL,
  `menu_order` tinyint(4) NOT NULL DEFAULT '0',
  `menu_father` tinyint(4) NOT NULL DEFAULT '0',
  PRIMARY KEY (`menu_id`)

How to use

 * The showMenu() function prints the menu
 * with all its sub menus
 * @params:	$ulclass -> common class to be applied in ul elements
		$liclass -> common class to be applied in li elements
		$father -> Father of each child menu. Pass '0' to print complete menu.
 * return:	string
showMenu($ulclass, $liclass, $father=0);

This is the simplest form of this menu, depending upon the requirements of the design it can be changed very easily.

Note: Please provide the credit to the author.

Good luck!!!

Follow me
Latest posts by Abhishek Gupta (see all)

Leave a Reply