search
HomeBackend DevelopmentPHP TutorialPHP infinite classification program code_PHP tutorial

PHP infinite classification program code_PHP tutorial

Jul 13, 2016 am 10:48 AM
phpcodeClassificationlong timeusdatanewsunlimitedprogram

Infinite classification is mostly used when classifying data. For example, our news or software channels may have various subcategories, but we don’t know these subcategories, so we have to use the infinite classification method. Let me introduce it to you.

First category (parent category)–>Second category (child category)–>Third category (grandchild category)

The more such kinship classifications, the more complicated and difficult it is to control the program and database. Classification processing and control at the same level is very simple, because only one database is needed to record this level of classification. , such as: system, news and other classifications, processing at this level is very simple, but for a website, the first-level classification is not enough, and it needs to be classified again, such as:

System–>linux,windows
News–>linux news,windows news

This classification will be clearer, at least it will make people understand that the system includes linux and windows, and the news includes linux news and windows news. In order to make the information clearer, I will continue to classify:

linux–>System tools, kernel, programming languages, development tools

When the classification reaches the third level, the processing of information becomes clearer. In other words, in order to process the information clearly, the more detailed the classification, the more convenient it is. This makes it easier to process information and make it easier for netizens to find what they need with a clear purpose. Data, but as the classification continues to be refined, it will become more and more difficult to control the program and database.

Difficulty 1: How to deal with these related kinship classifications in the database?
Difficulty 2: How to use php to complete this clear relationship?

This kind of multi-level and detailed classification is a problem that every PHP programmer must solve, because the classification problem of making a good and excellent website is inevitable, and solving this problem is quite complicated, among which the biggest The biggest problem is the classification processing of the database, because if the database is not handled properly, it will bring a huge workload and even have to re-plan the database...

This is not an exaggeration, because many people will use the first-level classification to build a database when processing databases. I also adopted this method to handle classification at that time, because most websites are classified into the third level, so There are only three classification databases in the database for processing. But when it is necessary to continue to classify downwards, the disadvantages of this approach are revealed, because the further down the classification, the workload and program volume will increase dramatically..

The method I want to introduce is how to use a classification database to create an infinite downward classification method. Readers who have used Windows all know that the windows folder can create an unlimited downward classification directory, and you can continue to create directories below the directory. , divided endlessly, Linux directory creation also has this function, the method I introduced is the same as this form.

Database planning
We talked about the complexity of classification earlier, so how to plan the database has become a very important step to achieve unlimited classification.

I once introduced the database planning of the forum. Yes, the forum can achieve unlimited follow-up. Unlimited classification is an extension of this form. Classification also has this kind of child-father relationship, so the classification database is how to establish and clearly define this There are several difficulties in the seed-parent relationship.

1) How to handle information storage of each category;
2) How to deal with the kinship relationship of classification;
3) How to handle inquiries for information;

The database processing of kinship relationships is similar to the database processing of forums. Here we build a type database to handle classification:

Create fields:
id(int): used to record the natural serial number of each category
uid(int): used to record the id number of the parent category of this category
type(char): name of category
roue_id (varchar): kinship tree, connecting with the id of :0:2:10:20: to indicate the kinship relationship
roue_char (varchar): Affinity tree, similar to: system: linux: development tools: gcc: (It doesn’t matter whether this field is present or not. In order to understand each affinity more conveniently, of course character expression is more direct than numerical expression ^o^, but it is best Add this field)

Such an unlimited category table has been established. Next, you need to establish a database to store information. It is most convenient to process and query a table, so here is a table to store information type_message:

id(int): the serial number of the message;
typeid(int): ID number of the category;
title(varchar): information title;
message(text): message content;
time: the time when the information was created;

These two data tables can complete the task of infinite classification (the auxiliary fields of the two tables are not added, readers can add them by themselves).

The rest of the tasks will be handled by php.

Program control
This step is the most complicated and laborious to implement the infinite classification function. First, let’s take a look at the steps that the program needs to complete:

1) Create categories for upload;
2) Create information to upload;
3) Clearly display each category and the relationship between them;
4) Query processing function;
5) How to handle the editing and deletion functions;

The most difficult of these five steps is the fifth step, because editing and deleting categories involves uniformity issues.

I will describe the program control of php one by one below:

1) Create categories and upload

Before introducing this function, let’s first introduce the explode() function. This is a string processing function used to decompose strings. The specific usage is as follows:

Decompose the numbers in "0:1:2:3:4"

$val="0:1:2:3:4";
$rid=explode(":",$val);

After being processed by the explode() function, all the numbers in $val are decomposed into the $rid array. When you want to quote, just print: echo “$rid[0],$rid[1],$rid[2 ]…”; That’s it. The explode( ) function plays a very important role in the entire classification process. Now let’s introduce the program control of non-current classification.

You can assume that there is a total classification of 0, and all categories are its descendants. Now let’s establish the first classification “system” and see how it is stored in the database:

id | uid | type | rout_id | rout_char
1 | 0 | System | 0:1 | System

Then divide "Linux" below:

id | uid | type | rout_id | rout_char
2 | 1 | Linux| 0:1:2 | SystemLinux

The above is the form of database storage. Now let’s complete the php code. This is very similar to the forum code. All we have to do is put the category id into uid, and the parent category’s uid into 0. Next Take a look at the code:

The code is as follows Copy code


.....
.....

//Set the default page
if (empty($func)) $func=="showtype";

//Set the uid of the parent category
if (empty($uid)) $uid=0;

//Database storage************************************************ *****
if ($func=="save"):

$fields = "";
$values ​​= "";

if ($id!="") {
$fields .= ",id";
$values.=",$id";
}

if ($uid!="") {
$fields .= ",uid";
$values.=",$uid";
}

if ($type!="") {
$fields .= ",type";
$values.=","$type"";
}

if ($route_id=="") {

//Get the route_id of the parent category
if ($uid!=0) {
$result = mysqlquery("select * from type where id=$uid");
$route_id=mysql_result($result,0,"route_id");
} else {
$routr_id="0";
}
$fields .= ",route_id";
//Form your own route_id
$route_id="$route_id:$id";
$values.=","$route_id"";
}

//Form your own route_char
if ($route_char!="") {
$fields .= ",route_char";
$route_char="$route_char:$type";
$values.=","$route_char"";
} else {
$fields .= ",route_char";
$route_char=$type;
$values.=","$route_char"";
}

$fields = substr($fields,1,strlen($fields)-1);
$values ​​= substr($values,1,strlen($values)-1);

$result = mysqlquery("insert into type ($fields) values ​​($values)");
...
endif; /* end save */

//Category upload************************************************ *****
if ($func=="createtype"):

//Get your own id
$result = mysqlquery("select * from type order by
id desc");
$num=mysql_numrows($result);
if (!empty($num)) {
$cat = mysql_result($result,0,"id");
} else {
$cat=0;
}

//Determine the status of the classification
if ($uid != 0) {
$result=mysql_query("select * from type where id=$uid");
$type=mysql_result($result,0,"type");
$route_char=mysql_result($result,0,"route_char");
} else {
$type="parent category";
}
echo "

";

echo "

";
echo "";
echo "";

echo "

";

echo "

Category:$type
Create category:
";
$cat=$cat+1;
echo "";
echo "";
echo "";
echo "
";
echo "
";
endif; /* end createtype */

//显示分类************************************************
if ($func=="showtype"):

echo "

";

//判断分类的状态
if ($uid!=0) {
$result=mysql_query("select * from type where id=$uid");
$type=mysql_result($result,0,"type");
} else {
$type="父分类";
}

echo "

";

echo "

";

$result=mysql_query("select * from type where uid=$uid");
$num=mysql_numrows($result);

if (!empty($num)) {
for ($i=0;$i

$id=mysql_result($result,$i,"id");
$type=mysql_result($result,$i,"type");

echo "

";
}
}

echo "

创建分类
$type
";
echo "$type";
echo "
";
endif; /* end showtype */
.....
.....

?>

 

 

以上的程序便完成了无限分类的基本创建,存储和显示,接着就是完善分类创建功能的各个部分了.

路径跟踪
前面已经介绍过了分类的创建实现方法,在分类表里记载了 rout_id 和 rout_char 这两个存储分类路径的信息,在不做任何处理的情况下,程序只能够顺序下到最底层的分类而无法倒退(当然可利用浏览器的 back 键倒退,但这对程序来说是不完整的),因此必须将 rout_id 和 rout_char 的信息分解出来完成实在的路径指示.

具体的做法,假如数据库记载了这么一条分类信息:

id:4
uid:2
type:开发工具
rout_id:0:1:2:4
rout_char:系统:linux:开发工具

当程序走到分类’开发工具’上时,除了要求显示路径信息外还要求能够去到路径上的任一分类中,该怎么做能?这里就需要用到 explode() 函数了.因为 rout_id 和 rout_char 是对应关系的,所以可将它们分解:

 

 代码如下
 代码如下 复制代码

 

$path=explode(":",$rout_id);
$path_gb=explode(":",$rout_char);

复制代码

 

$path=explode(":",$rout_id);

$path_gb=explode(":",$rout_char);

 代码如下 复制代码

 

for ($i=0;;$i++) {
$a=$i+1;
echo " href=$php_self?func=showtype&uid=",$path[$a],">",$path_gb[$i],":";
if (empty($path_gb[$i])) {
break;
}
}

    这时所有分类信息都被分解了,现在要做的就是以链接的方式还原路径信息:  
 代码如下 复制代码
  for ($i=0;;$i++) { $a=$i+1; echo " href=$php_self?func=showtype&uid=",$path[$a],">",$path_gb[$i],":"; if (empty($path_gb[$i])) { break; } }


The above code implements the function of adding links to restore paths. Because it implements infinite classification, there is no upper limit, so there is no range limit in for($i=0;;$i++), and the loop exit is set. The condition is that the value in $path_gb[$i] is empty. Just insert this code into the program block of the category display layout:

The code is as follows
 代码如下 复制代码

 


.....
.....
//显示分类************************************************
if ($func=='showtype'):

echo "

";

//判断分类的状态
if ($uid!=0) {
$result=mysql_query("select * from type where id=$uid");
$type=mysql_result($result,0,"type");

//******** 新加入的代码 ***************
$rout_id=mysql_result($result,0,"rout_id");
$rout_char=mysql_result($result,0,"rout_char");
$path=explode(":",$rout_id);
$path_gb=explode(":",$rout_char);
echo "

";
//******** end ***********************

} else {
$type='父分类';
}

echo "

";

echo "

";

$result=mysql_query("select * from type where uid=$uid");
$num=mysql_numrows($result);

if (!empty($num)) {
for ($i=0;$i

$id=mysql_result($result,$i,"id");
$type=mysql_result($result,$i,"type");

echo "

";
}
}

echo "

";
for ($i=0;;$i++) {
$a=$i+1;
echo " href=$php_self?func=showtype&uid=",$path[$a],">",$path_gb[$i],":";
if (empty($path_gb[$i])) {
break;
}
}
echo "
创建分类
$type
";
echo "$type";
echo "
";
endif; /* end showtype */
.....
.....
?>

 

 

Copy code

.....

.....

//Display categories********************************************** ** echo ""; //Determine the status of the classification if ($uid!=0) { $result=mysql_query("select * from type where id=$uid"); $type=mysql_result($result,0,"type"); //******** 新加入的代码 *************** $rout_id=mysql_result($result,0,"rout_id"); $rout_char=mysql_result($result,0,"rout_char"); $path=explode(":",$rout_id); $path_gb=explode(":",$rout_char); echo ""; //******** end *********************** } else { $type='父分类'; } echo ""; echo ""; $result=mysql_query("select * from type where uid=$uid"); $num=mysql_numrows($result); if (!empty($num)) { for ($i=0;$i $id=mysql_result($result,$i,"id"); $type=mysql_result($result,$i,"type"); echo ""; } } echo "
";
for ($i=0;;$i++) {
$a=$i+1; echo " href=$php_self?func=showtype&uid=",$path[$a],">",$path_gb[$i],":"; if (empty($path_gb[$i])) { break; } } echo "
创建分类
$type
"; echo "$type"; echo "
"; endif; /* end showtype*/ ..... ..... ?> After completing this function block, you can continue to display the classified information http://www.bkjia.com/PHPjc/632808.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632808.htmlTechArticleUnlimited classification Most of the time when classifying data, like our news or software channel, there may be various subcategories, but for We don’t know this kind of subcategory, so we have to use the infinite classification method. Below I...
Statement
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
How do you set the session cookie parameters in PHP?How do you set the session cookie parameters in PHP?Apr 22, 2025 pm 05:33 PM

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

What is the main purpose of using sessions in PHP?What is the main purpose of using sessions in PHP?Apr 22, 2025 pm 05:25 PM

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How can you share sessions across subdomains?How can you share sessions across subdomains?Apr 22, 2025 pm 05:21 PM

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

How does using HTTPS affect session security?How does using HTTPS affect session security?Apr 22, 2025 pm 05:13 PM

HTTPS significantly improves the security of sessions by encrypting data transmission, preventing man-in-the-middle attacks and providing authentication. 1) Encrypted data transmission: HTTPS uses SSL/TLS protocol to encrypt data to ensure that the data is not stolen or tampered during transmission. 2) Prevent man-in-the-middle attacks: Through the SSL/TLS handshake process, the client verifies the server certificate to ensure the connection legitimacy. 3) Provide authentication: HTTPS ensures that the connection is a legitimate server and protects data integrity and confidentiality.

The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.