


Detailed explanation of infinite classification examples in php mysql_PHP tutorial
Detailed explanation of examples of infinite classification in php mysql
This article mainly introduces the method of realizing infinite classification in php mysql, and analyzes the mysql database design, database operation and infinite classification with examples. The specific implementation steps are of great practical value. Friends in need can refer to them
The example in this article describes the method of realizing unlimited classification in php mysql. Share it with everyone for your reference. The specific analysis is as follows:
1. The database performs unique indexing by setting the parent class ID, and then uses recursive calls of functions to achieve unlimited classification;
2. The database design is arranged in a specific format, and then uses mysql to query the key function: concat. The program implementation is relatively simple. First, we assume that there is such a three-level classification, News→PHP News→PHP6.0 is out.
If we want to find the news "PHP6.0 is out", we can click on the news first, and then click on the PHP news to find out. In other words, we can go down level by level through the grandfather class. In turn, as long as we know the parent class of a subclass, we can find it. In this way, when designing the database, we can design an additional field for the parent class id to achieve unlimited classification.
The database code is as follows:
Here we create a table "class"
The code is as follows:
`id` int(11) NOT NULL auto_increment COMMENT 'category id',
`f_id` int(11) NOT NULL COMMENT 'parent id',
`name` varchar(25) collate gbk_bin NOT NULL COMMENT 'Category name',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=gbk COLLATE=gbk_bin AUTO_INCREMENT=1 ;
First, we insert the "News" category into the database. Because "News" is the largest category and there is no parent category on it, so I set its f_id to 0.
The code is as follows:
Then we insert the category 'PHP News' into the database. The id of its parent category 'News' is 1, so its f_id is set to 1.
The code is as follows:
Then we insert the category 'PHP 6.0 is out' into the database. The id of its parent category 'PHP News' is 2, so its f_id is set to 2.
The code is as follows:
Similarly, we can insert categories all the way down, thus reaching infinite categories.
We can find that the key to inserting a category is to find the id of the parent category of this category, and then use it as the value of the f_id field of this category.
Suppose you want to insert the category 'Technology' at the same level as 'News', that is to say it is also the largest category and there is no parent category above it, then its f_id is also set to 0;
Copy the code The code is as follows:
There is another category 'PHP Technology' under 'Technology', so how do we insert it? First find the id of the parent class 'Technology' of 'PHP Technology', and then use it as the value of its own f_id field.
The code is as follows:
Seeing this, everyone should understand how to insert each category into the database, so I won’t give examples. We already know how to insert each category into the database, so how do we list each category?
The code is as follows:
$db=new mysqli("localhost","root","","news_php100"); //Instantiate a database connection. Before using this, make sure that the mysqli class library has been loaded, or connect using mysql_connect.
if(mysqli_connect_errno()){
echo "Link failed:".mysqli_connect_error();
exit(); }
$db->query("set names utf8");
$result=$db->query("select name from class where f_id=0"); //Find the category with f_id=0, that is, find each major category.
while($row=$result->fetch_assoc()){
echo $row['name']."
"; //This will loop out each major category.
}
//Similarly we can loop out the subcategories of news.
$result=$db->query("select * from class where f_id=1"); //Find the category of f_id=1, that is, find the subcategory of 'News'.
while($row=$result->fetch_assoc()){
echo $row['name']."
"; //This loops out the subclasses of 'News'. Note: only subclasses, excluding grandchild classes.
}
//Writing here, we will find a problem. If this classification is a 10-level classification, do we have to write 10 loops to cycle out each of its subcategories? If there are more levels of classification, it is obviously unrealistic to write like this.
//Then what is the solution? We can write a recursive function, pass in f_id as a parameter, and continuously loop through the value of each f_id, that is to say, loop out the subclass of each f_id value.
//First we save the values of each category in a two-dimensional array, which is useful in the following recursive function.
$result=$db->query("select * from class");
while($row=$result->fetch_assoc()){
$arr[]=array($row[id],$row[f_id],$row[name]); //Each row saves the information of a category's id, f_id, and name.
}
function fenlei($f_id=0){ //$f_id is initialized to 0, that is, the cycle starts from the maximum classification.
global $arr; //Declare $arr as a global variable before it can be referenced in the function.
for($i=0;$i
echo $arr[$i][2]."
"; //$arr[$i][1] represents the value of the name of the $i-th category.
fenlei($arr[$i][0]); //$arr[$i][1] represents the value of the id of the $i-th category. Perform recursion, that is, use your own id as the f_id parameter to recycle your own subclasses.
}
}
}
?>
The three fields id, parentid, name, the algorithm is also very simple and recursive. In the past, it was very stupid when using recursion, I should say extremely stupid, because in recursion, all the subclasses were obtained by querying the data table. Recently, I got the idea and thought of a The method that everyone on earth can think of, the following is the code, a class, the code is as follows:
Copy the code The code is as follows:
/**
* All classification information queried from the database
* @var array
*/
var $arr;
/**
* The following format
* var $arr = array(
1 => array('id'=>'1','parentid'=>0,'name'=>'First-level column one'),
2 => array('id'=>'2','parentid'=>0,'name'=>'First-level column two'),
3 => array('id'=>'3','parentid'=>1,'name'=>'Second-level column one'),
);*/
/**
* Output structure
* @var array
*/
var $tree = array();
/**
* Depth of tree recursion
* @var int
*/
var $deep = 1;
/**
* Generate tree-shaped modification symbols
* @var array
*/
var $icon = array('│','├','└');
/**
* Generate a subordinate tree structure of the specified id
* @param int $rootid To get the id of the tree structure
* @param string $add prefix used in recursion
* @param bool $parent_end identifies whether the parent category is the last one
*/
function getTree($rootid = 0,$add = ”,$parent_end =true){
$is_top = 1;
$child_arr = $this->getChild($rootid);
if(is_array($child_arr)){
$cnt = count($child_arr);
foreach($child_arr as $key => $child){
$cid = $child['id'];
$child_child = $this->getChild($cid);
if($this->deep >1){
if($is_top == 1 && $this->deep > 1){
$space = $this->icon[1];
if(!$parent_end)
$add .= $this->icon[0];
else $add .= ' ';
}
if($is_top == $cnt){
$space = $this->icon[2];
$parent_end = true;
}else {
$space = $this->icon[1];
$parent_end = false;
}
}
$this->tree[] = array('spacer'=>$add.$k.$space,
'name'=>$child['name'],
'id'=>$cid
);
$is_top ;
$this->deep ;
if($this->getChild($cid))
$this->getTree($cid,$add,$parent_end);
$this->deep–;
}
}
return $this->tree;
}
/**
* Get the lower-level classification array
* @param int $root
*/
function getChild($root = 0){
$a = $child = array();
foreach($this->arr as $id=>$a){
if($a['parentid'] == $root){
$child[$a['id']] = $a;
}
}
return $child?$child:false;
}
/**
* Set source array
* @param $arr
*/
function setArr($arr = array()){
$this->arr = $arr;
}
}
?>
通过一次查询把结构保存进一个数组,再数组进行递归运算,无疑极大的提高了程序运行效率,使用代码很简单.
希望本文所述对大家的php程序设计有所帮助。

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Zend Studio 13.0.1
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6
Visual web development tools