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 they do not have an ideal ready-made component. In general,ProgramDevelopers mainly use JavaScript to implement some simple tree-structured menus. 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 required to be rewritten, so 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 describes how to process a dynamic tree menu written in PHP, MySQL, and JavaScript.CodeIf 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 "";
// If the menu item has a submenu, add the Javascript onclick statement
If (mysql_num_rows ($ result_sub)> 0)
{< br> echo " ";
echo " ";
}< br> else
{< br> echo " ";
echo "";
}< br> // if no sub-menu exists for this menu item and a super connection is specified
// otherwise, only the menu name
if ($ menu [url]! = "")
echo " $ menu [name] ";
else
echo $ menu [name];
echo "


";

// 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 :)

Related Article

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.