Home > Backend Development > PHP Tutorial > A simpler infinite level category menu code

A simpler infinite level category menu code

巴扎黑
Release: 2023-03-02 16:54:02
Original
1343 people have browsed it

A simpler infinite-level category menu code

First of all, I would like to thank terry39 for his guidance. I have nothing to do on New Year's Day, so I will simply implement the principle he said. The key to this program is that the design of the data table is very simple. It is unique. It does not require recursion. You can list the menu with a simple SQL statement. Take a look at how this data table is designed:
The database fields are roughly as follows:
----------------- -------------------------------------------------- ----------------
id number
fid parent category number
name category name
path category path, with id as the node, composed like,1,2,3,4, like this String
------------------------------------------------- ------------------------------------

It can be assumed that there is the following data

id fid name path
------------------------------------------------- ---
1 0 Category 1,1,
2 0 Category 2,2,
3 1 Category 1-1,1,3,
4 1 Category 1-2,1,4,
5 2 Category 2-1 ,2,5,
6 4 Category 1-2-1 ,1,4,6,
------------------------------ --------------------------
I am lazy this time, I only use one page. Fortunately, the code is not long, and all the codes are encapsulated in classes (not necessary , but I also want to get familiar with OO, haha!), let’s take a look at the page code:

<?php
classmenu{
//创建构造函数,作用:数据库连接并选择相应数据库
publicfunction__construct(){
$dbhost="localhost";
$dbuser="root";
$dbpassword="7529639";
$dbname="menu";
mysql_connect($dbhost,$dbuser,$dbpassword)ordie("error!");
mysql_query("SETNAMES&#39;GBK&#39;");
mysql_select_db($dbname);
}
//执行SQL语句函数
privatefunctionquery($sql){
returnmysql_query($sql);
}
//取得结果集数组函数
privatefunctionloop_query($result){
returnmysql_fetch_array($result);
}
//列出菜单列表函数
publicfunctionmenulist(){
$sql="select*fromlistorderbypath";
$result=$this->query($sql);
while($rows=$this->loop_query($result)){
if(substr_count($rows[&#39;path&#39;],&#39;,&#39;)>2){
for($i=0;$i<(substr_count($rows[&#39;path&#39;],&#39;,&#39;)-2);$i++)
echo&#39;&#39;;
}
echo$rows[&#39;name&#39;].&#39;<br>&#39;;
}
}
//创建析构函数,作用:关闭数据库连接
publicfunction__destruct(){
returnmysql_close();
}
}
$db=newmenu();//生成实例
$db->menulist();//调用方法生成菜单
?>
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template