Implement a dynamic tree menu based on php and MySQL using function Recursion

Source: Internet
Author: User

Tree menus are widely used in many desktop application systems. The main advantage of tree menus is that the structure is clear, which helps users know their location clearly. However, tree menu applications on the web can be directly used because there is no ideal ready-made component. In general, programmers mainly implement simple tree-structure menus through JavaScript, however, these menus are usually pre-defined for each menu item and the hierarchical relationship between menu items, which is not conducive to expansion. Once another menu structure is required, it is often necessary to re-compile the menu, therefore, it is not very convenient to use.

After studying the recursion of functions, I found that this kind of tree menu can be implemented through recursive functions, so that the display of tree menus can be dynamically changed without the limit of series. The following is the processing code of a dynamic tree menu written in php, MySQL, and JavaScript. If you are interested, let's take a look at how I implement it with me :)

First, we need a database. In this database, we create the following table:


Create table menu (
Id tinyint (4) not null auto_increment,
Parent_id tinyint (4) DEFAULT '0' not null,
Name varchar (20 ),
Url varchar (60 ),
Primary key (id)
);


This table
Id is Index
Parent_id is used to save the ID number of the top-level menu. If it is a top-level menu, it is 0.
Name is the name of the menu, that is, the menu content to be displayed on the page.
Url if a menu is the last menu, you need to specify the url address of the connection. This field is used to save this address. Other non-last menu, this field is blank

Now that the database is ready, you can add some records. Below are some records used during the test:

Insert into menu VALUES ('1', '0', 'personnel management ','');
Insert into menu VALUES ('2', '0', 'communication communication ','');
Insert into menu VALUES ('3', '1', 'file management ','');
Insert into menu VALUES ('4', '1', 'attendance management', 'HTTP: // localhost/personal/attendance. php ');
Insert into menu VALUES ('5', '2', 'address ','');
Insert into menu VALUES ('6', '2', 'network conferencing ','');
Insert into menu VALUES ('7', '3', 'add files', 'HTTP: // localhost/personal/add_achive.php ');
Insert into menu VALUES ('8', '3', 'queryfile', 'HTTP: // localhost/personal/search_archive.php ');
Insert into menu VALUES ('9', '3', 'delete files', 'HTTP: // localhost/personal/delete_archive.php ');
Insert into menu VALUES ('10', '5', 'add communication record ', 'HTTP: // localhost/communication/add_address.php ');
Insert into menu VALUES ('11', '5', 'query communication record ', http: // localhost/communication/search_address.php ');
Insert into menu VALUES ('12', '5', 'delete communication record ', http: // localhost/communication/delete_address.php ');
Insert into menu VALUES ('13', '6', 'convene a meeting ', 'HTTP: // localhost/communication/convence_meeting.php ');
Insert into menu VALUES ('14', '6', 'conference query', 'HTTP: // localhost/communication/search_meeting.php ');


When adding a record, you must note that the parent_id of a non-level menu must be specified as the ID of the parent menu; otherwise, your menu will not be displayed :)

Okay! With the database, the menu is read from the database through php and JavaScript and displayed :)

1. JavaScript script:
Function ShowMenu (MenuID)
{
If (MenuID. style. display = "none ")
{
MenuID. style. display = "";
}
Else
{
MenuID. style. display = "none ";
}
}

This script is very simple. It is used to respond to the event of clicking a menu.

2. CSS file:
<! -- Table style -->
TD {
FONT-FAMILY: "Verdana", ""; FONT-SIZE: 12px; LINE-HEIGHT: 130%; letter-spacing: 1px
}

<! -- Super connection style -->
A: link {
COLOR: #990000; FONT-FAMILY: "Verdana", ""; FONT-SIZE: 12px; TEXT-DECORATION: none; letter-spacing: 1px
}
A: visited {
COLOR: #990000; FONT-FAMILY: "Verdana", ""; FONT-SIZE: 12px; TEXT-DECORATION: none; letter-spacing: 1px
}
A: active {
COLOR: #990000; FONT-FAMILY: "Verdana", ""; FONT-SIZE: 12px; TEXT-DECORATION: none; letter-spacing: 1px
}
A: hover {
COLOR: # ff0000; FONT-FAMILY: "Verdana", ""; FONT-SIZE: 12px; TEXT-DECORATION: underline; letter-spacing: 1px
}

<! -- Other styles -->
. Menu {
COLOR: #000000; FONT-FAMILY: "Verdana", ""; FONT-SIZE: 12px; CURSOR: hand
}


Some basic style information is defined, such as the font, color, and super-connected style. If you want to change the style, you just need to modify it here!

3. The following is my php page!

<Html>
<Head>
<Link hrefw.'style.css 'rel = stylesheet>
<Script language = "JavaScript" src = "TreeMenu. js"> </script>
</Head>
<Body>
<? Php
// Set basic variables
$ GLOBALS ["ID"] = 1; // used to track the ID of the drop-down menu
$ Layer = 1; // used to track the level of the current menu

// Connect to the database
$ Con = mysql_connect ("localhost", "root ","");
Mysql_select_db ("work ");

// Extract the first-level menu
$ SQL = "select * from menu where parent_id = 0 ";
$ Result = mysql_query ($ SQL, $ Con );

// If a level-1 menu exists, the Start menu is displayed.
If (mysql_num_rows ($ result)> 0) ShowTreeMenu ($ Con, $ result, $ layer, $ ID );


// ================================================ ========
// ShowTreeMenu ($ con, $ result, $ layer)
// $ Con: Database Connection
// $ Result: Set of menu records to be displayed
// Layer: the level of the menu to be displayed
// ================================================ ========
Function ShowTreeMenu ($ Con, $ result, $ layer)
{
// Obtain the number of items to be displayed
$ Numrows = mysql_num_rows ($ result );

// Start to display the menu. Each sub menu is represented by a table.
Echo "<table cellpadding = '0' cellspacing = '0' border = '0'> ";

For ($ rows = 0; $ rows <$ numrows; $ rows ++)
{
// Import the content of the current menu item into an array
$ Menu = mysql_fetch_array ($ result );

// Extract the sub-menu record set of the menu item
$ SQL = "select * from menu where parent_id = $ menu [id]";
$ Result_sub = mysql_query ($ SQL, $ Con );

Echo "<tr> ";
// If this menu item has a submenu, add the JavaScript onClick statement
If (mysql_num_rows ($ result_sub)> 0)
{
Echo "<td width = '20'> </td> ";
Echo "<td class = 'menu 'onclick = 'javascript: ShowMenu (Menu". $ GLOBALS ["ID"]. "); '> ";
}
Else
{
Echo "<td width = '20'> </td> ";
Echo "<td class = 'menu '> ";
}
// If this menu item does not have a sub-menu and a super connection address is specified, it is specified as a super connection,
// Otherwise, only the menu name is displayed.
If ($ menu [url]! = "")
Echo "<a href = '$ menu [url]'> $ menu [name] </a> ";
Else
Echo $ menu [name];
Echo"
</Td>
</Tr>
";

// If this menu item has a sub menu, the sub menu is displayed
If (mysql_num_rows ($ result_sub)> 0)
{
// Specify the sub-menu ID and style to correspond to the onClick statement
Echo "<tr id = Menu". $ GLOBALS ["ID"] ++. "style = 'display: none'> ";
Echo "<td width = '20'> </td> ";
Echo "<td> ";
// Add the level to 1
$ Layer ++;
// Call the ShowTreeMenu () function recursively to generate a sub-menu
ShowTreeMenu ($ Con, $ result_sub, $ layer );
// After the sub-menu is processed, return to the upper layer of recursion and subtract 1 from the level.
$ Layer --;
Echo "</td> </tr> ";
}
// Continue to display the next menu item
}
Echo "</table> ";
}
?>
</Body>
</Html>


In the above php page, I defined a function ShowTreeMenu (). By calling this function, each menu item is recursively called from the database and displayed on the page :)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.