Php unlimited classification code and principles

Source: Internet
Author: User
Tags explode mysql tutorial php code php tutorial strlen

First category (parent category) --> second category (sub-category) --> third category (Sun category)

The more kinship classification, the more complex and difficult it is to control programs and database tutorials. classification processing and control at the same level is very simple, because only one database is required to record the classification at this level, such as system and news, processing at this level is very simple, but for a website, level-1 classification is not enough, and further classification is required.
// Create a table "class"
Create table 'class '(
'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' big classification into the database. Because 'news' is the largest category and no parent class exists, I set f_id to 0.
Insert into 'class' ('id', 'F _ id', 'name') VALUES (1, 0, 'news '); // The id field automatically increases without writing a value.
 
// Then we insert the 'php News 'category into the database. The id of its parent class 'news' is 1, so its f_id is set to 1.
Insert into 'class' ('id', 'F _ id', 'name') VALUES (2, 1, 'php News ');
 
// Then we insert the 'php6. 0' category into the database. The id of its parent class 'php news' is 2, so its f_id is set to 2.
Insert into 'class' ('id', 'F _ id', 'name') VALUES (3, 2, 'php6. 0 ');
 
// Similarly, we can insert categories all the time to achieve unlimited classification.
// We can find that the key to inserting a category is to find the id of the parent class of the category and use it as the value of the f_id field of the category.
// Assume that you want to insert the same level of classifier as 'news'. That is to say, it is also the largest classification. If there is no parent class above, its f_id is also set to 0;
Insert into 'class' ('id', 'F _ id', 'name') VALUES (4, 0, 'technical ');
 
// There is another classification of 'php' under 'tech'. So how can we insert it? First, find the id of the parent class 'tech' of 'php, and use it as the value of your f_id field.
Insert into 'class' ('id', 'F _ id', 'name') VALUES (5, 4, 'php techno ');
 
// When we see this, we should all understand how to insert various categories into the database. I will not give an example.

We already know how to insert each category into the database, and how to list each category?

<? Php Tutorial
Header ("Content-type: text/html; charset = utf-8 ");
$ Db = new mysql tutorial I ("localhost", "root", "", "news_php100"); // instantiate a database connection. Before using this method, make sure that the mysqli class library has been loaded or you can use mysql_connect to 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"); // you can find the f_id = 0 category, that is, to find each category.
While ($ row = $ result-> fetch_assoc ()){
Echo $ row ['name']. "<br>"; // loop every category.
}
// We can loop the subcategories of news.
$ Result = $ db-> query ("select * from class where f_id = 1"); // you can find the classification of f_id = 1, that is, the subclass of 'news.
While ($ row = $ result-> fetch_assoc ()){
Echo $ row ['name']."
"; // In this way, the subcategory of 'news' is recycled. Note: it is only a subclass, not a child class.
}
// Write it here and we will find a problem. If this category is of the 10th level, do we need to write 10 loops to cycle every subclass of it? If it is more multi-level classification, it is obviously unrealistic to write.
// What can be done? We can write a recursive function that uses f_id as a parameter and continuously loops through each f_id value, that is, loops through the subclass of each f_id value.
// First, we store the values of each classification in a two-dimensional array, which is useful in the following recursive functions.
$ Result = $ db-> query ("select * from class ");
While ($ row = $ result-> fetch_assoc ()){
$ Arr [] = array ($ row [id], $ row [f_id], $ row [name]); // Each row stores a category id, f_id, 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 for reference in the function.
For ($ I = 0; $ I <count ($ arr); $ I ++) {// Loops each category.
If ($ arr [$ I] [1] = $ f_id) {// $ arr [$ I] [1] indicates the f_id value of the $ I + 1 category. Start with $ f_id = 0, that is, output the f_id = 0 category.
Echo $ arr [$ I] [2]. "<br>"; // $ arr [$ I] [1] indicates the name of the $ I + 1 category.
Fenlei ($ arr [$ I] [0]); // $ arr [$ I] [1] indicates the id value of the $ I + 1 category. Recursion, that is, using your id as the f_id parameter to recycle its subclass.
}
}
}
?>


Before introducing this function, we will first introduce the explode () function, which is a string processing function used to break down strings. The specific usage is as follows:

Break down the numbers in "0: 1: 2: 3: 4"

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

After processing by the explode () function, all the numbers in $ val are decomposed into the $ rid array. To reference them, print the following: echo "$ rid [0], $ rid [1], $ rid [2]... "; that's all. the explode () function plays an important role in the entire classification process. Now we will introduce program control for non-existing classification.

Assume that a total Category is 0, and all categories are its descendant categories. Now we will create the first category "system" to see its storage format in the database:

Id | uid | type | rout_id | rout_char
1 | 0 | system | 0: 1 | system

Next we will share the following "Linux ":

Id | uid | type | rout_id | rout_char
2 | 1 | Linux | system: Linux

The above is the form of database storage. Now we can complete the php code, which is very similar to the Forum code. All we need to do is to put the classification id into the uid, the uid of the parent category is 0. Let's look at the code below:

<?
.....
.....

// Set the hosts 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 = ""){

// Obtain 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 */


// Upload by category ************************************ ************
If ($ func = "createtype "):

// Obtain your own id
$ Result = mysqlquery ("select * from type order
Id desc ");
$ Num = mysql_numrows ($ result );
If (! Empty ($ num )){
$ Cat = mysql_result ($ result, 0, "id ");
} Else {
$ Cat = 0;
}

// Determine the classification status
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 "<form action =" $ PHP_SELF? Func = save "METHOD = POST> ";

Echo "<table> ";
Echo "<tr> <td> Category: $ type </td> </tr> ";
Echo "<tr> <td> create Category: <input type = text name =" type "SIZE = 10 MAXLENGTH = 100> </td> </tr> ";

Echo "<tr> <td> ";
$ Cat = $ cat + 1;
Echo "<input type = hidden name = id value =" $ cat "> ";
Echo "<input type = hidden name = uid value =" $ uid "> ";
Echo "<input type = hidden name = route_char value =" $ route_char "> ";
Echo "<input type = submit NAME =" Save "VALUE =" Save "> </td> </tr> ";

Echo "</table> ";
Echo "</form> ";
Endif;/* end createtype */

// Display the category ************************************ ************
If ($ func = "showtype "):

Echo "<table> ";

// Determine the classification status
If ($ uid! = 0 ){
$ Result = mysql_query ("select * from type where id = $ uid ");
$ Type = mysql_result ($ result, 0, "type ");
} Else {
$ Type = "parent category ";
}

Echo "<tr> <td> <a href =" $ php_self? Func = createtype & uid = $ uid "> Create a category </a> </td> </tr> ";

Echo "<tr> <td> $ type </td> </tr> ";

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

If (! Empty ($ num )){
For ($ I = 0; $ I <$ num; $ I ++ ){

$ Id = mysql_result ($ result, $ I, "id ");
$ Type = mysql_result ($ result, $ I, "type ");

Echo "<tr> <td> ";
Echo "<a href =" $ php_self? Func = showtype & uid = $ id "> $ type </a> ";
Echo "</td> </tr> ";
}
}

Echo "</table> ";
Endif;/* end showtype */
.....
.....

?>

The above program completes the basic creation, storage, and display of the unlimited classification, and then completes the various parts of the classification creation function.
4. Path tracking
------------------------------------------------------------
We have already introduced how to create a category. In the classification table, information about the two storage paths rout_id and rout_char is recorded. Without any processing, the program can only be sorted to the bottom-layer classification and cannot be regressed (of course, the back key of the browser can be used for regressing, but this is incomplete for the program ), therefore, the information of rout_id and rout_char must be decomposed to complete the actual path indication.

The specific procedure is as follows:

Id: 4
Uid: 2
Type: development tool
Rout_id: 0: 1: 2: 4
Rout_char: System: linux: Development tools

When the program goes to the classification 'development tools', in addition to displaying the path information, it also needs to be able to go to any category on the path. How can this problem be solved? Here we need to use the explode () function. Because rout_id and rout_char correspond to each other, we can break them down:

$ Path = explode (":", $ rout_id );
$ Path_gb = explode (":", $ rout_char );

At this time, all the classification information is broken down. Now we need to restore the path information by link:
[Php]
For ($ I = 0; $ I ++ ){
$ A = $ I + 1;
Echo "<
Href = $ php_self? Func = showtype & uid = ", $ path [$ a],"> ", $ path_gb [$ I]," </a> :";
If (empty ($ path_gb [$ I]) {
Break;
}
}
[/Php]
The above code adds a link to restore the path, because the implementation is infinite classification, there is no limit, so in for ($ I = 0 ;; $ I ++) has no range restrictions, but the condition for loop exit is that the value in $ path_gb [$ I] is null, insert this code into the program block of the category display layout:
[Php]
<?
.....
.....
// Display the category ************************************ ************
If ($ func = 'showtype '):

Echo "<table> ";

// Determine the classification status
If ($ uid! = 0 ){
$ Result = mysql_query ("select * from type where id = $ uid ");
$ Type = mysql_result ($ result, 0, "type ");

// ********* Newly added code ***************
$ 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 "<tr> <td> ";
For ($ I = 0; $ I ++ ){
$ A = $ I + 1;
Echo "<
Href = $ php_self? Func = showtype & uid = ", $ path [$ a],"> ", $ path_gb [$ I]," </a> :";
If (empty ($ path_gb [$ I]) {
Break;
}
}
Echo "</td> </tr> ";
***********************

} Else {
$ Type = 'parent category ';
}

Echo "<tr> <td> <a href = '$ php_self? Func = createtype & uid = $ uid '> Create a category </a> </td> </tr> ";

Echo "<tr> <td> $ type </td> </tr> ";

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

If (! Empty ($ num )){
For ($ I = 0; $ I <$ num; $ I ++ ){

$ Id = mysql_result ($ result, $ I, "id ");
$ Type = mysql_result ($ result, $ I, "type ");

Echo "<tr> <td> ";
Echo "<a href = '$ php_self? Func = showtype & uid = $ ID'> $ type </a> ";
Echo "</td> </tr> ";
}
}

Echo "</table> ";
Endif;/* end showtype */
.....
.....
?>
[/Php]
After this function block is completed, you can continue to display the classification information.

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.