- CREATE TABLE ' type ' (
- ' id ' int (one) not NULL auto_increment,
- ' FID ' int (one) not NULL DEFAULT ' 0 ',
- ' Name ' varchar (not NULL),
- PRIMARY KEY (' id ')
- )
Copy CodeSecond, add several top-level categories to add
- INSERT into ' type ' (' id ', ' fid ', ' name ') VALUES (NULL, ' 0 ', ' phone ');
- INSERT into ' type ' (' id ', ' fid ', ' name ') VALUES (NULL, ' 0 ', ' computer ');
- INSERT into ' type ' (' id ', ' fid ', ' name ') VALUES (NULL, ' 0 ', ' shoes ');
- INSERT into ' type ' (' id ', ' fid ', ' name ') VALUES (NULL, ' 0 ', ' clothes ');
Copy CodeHere Fid=0 is representative of the top category Then add several subcategories for {computer}
- INSERT into ' type ' (' id ', ' fid ', ' name ') VALUES (null, ' 2 ', ' Desktop '), (null, ' 2 ', ' notebook ');
Copy CodeHere fid=2,2 this ID is the ID of the category {computer}, if it is a subcategory that adds {shoes} fid=3 the same as {notebook} to add subcategories fid=6
- INSERT into ' type ' (' id ', ' fid ', ' name ') VALUES (null, ' 6 ', ' Ausu '), (null, ' 6 ', ' hp ');
Copy CodeThird, delete if you want to delete the category {notebook}, you can:
- DELETE from ' type ' WHERE ' ID ' =6
Copy Code{Notebook} sub-classification also remember to do the corresponding processing
Function del ($FID) {
- $sql = "SELECT * from ' type ' WHERE ' fid ' = $fid";
- $rs =mysql_query ($sql);
- for ($i = 0; $i < count ($rs); $i + +) {
- $sql = "DELETE from ' type ' WHERE ' id ' ={$rs [$i] [' ID ']}";
- mysql_query ($sql);
- Del ($rs [' id ']);//recursion
- }
- }
Del (6);//Perform operation
Copy CodeWhy is it so troublesome to use recursion instead of deleting it directly
- DELETE from ' type ' WHERE ' FID ' =6
Copy CodeSo you can delete {Ausu}, {hp} directly? But suppose {Ausu} has a subcategory {A1},{A1} that also has a subclass {A2}, which cannot be completely deleted without recursion. Third, find 1. Find subcategories for {computer}
- SELECT * from ' type ' WHERE ' FID ' =2
Copy Code2. Find all sub-categories for {computer}
Function sel ($FID) {
- $sql = "SELECT * from ' type ' WHERE ' fid ' = $fid";
- $rs =mysql_query ($sql);
- for ($i = 0; $i < count ($rs); $i + +) {
- echo $rs [$i] [' name '];
- SEL ($rs [$i] [' id ']);//recursion
- }
- }
SEL (2);
Copy CodeIv. Practical application Add a field ' tid ' to the data table, and the field value is the ID of the category ' type ' table to which the record belongs. Must be ID cannot be name, because the value of name may change. For example, query for items that belong to the {computer} Category:
- SELECT * from ' goods ' WHERE ' tid ' =2
Copy CodeLet's introduce these and hope to help you. |