Category subcategory tree view
provides a user-friendly way to list the parent and child categories. The category and their subcategory are easily separated by a tree structure. The categories tree view is always recommended to display an infinite level of categories and subcategories.
In this tutorial, we will show you how to create dynamic category subcategory tree using PHP
and MySQL. The recursive category tree
is very useful to list n level categories in a dropdown. The example code helps you to build n level category subcategory dropdown in PHP. The dynamic categories data will be retrieved from the MySQL database and listed in a parent-child category tree format.
Create Database Table
To store categories and subcategories, a table needs to be created in the database. The following SQL creates a categories
table in the MySQL database.
CREATE TABLE `categories` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`parent_id` int(11) NOT NULL DEFAULT '0',
`name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1' COMMENT '1:Active, 0:Inactive',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
The parent_id
column specifies whether the category is parent or child. If parent_id is 0, it will be a parent category. Otherwise, it will be a child category and the ID is the parent of this category.
Database Configuration (dbConfig.php)
The dbConfig.php
file is used to connect and select the database. Specify the database host ( $dbHost
), username ( $dbUsername
), password ( $dbPassword
), and name ( $dbName
) as per your MySQL credentials.
connect_error) {
die("Connection failed: " . $db->connect_error);
}
?>
PHP Recursive Function to Generate Parent/Child Tree
The categoryTree()
function generates an n level category subcategory tree using PHP. It will create the dropdown options for categories tree.
$parent_id
– Optional. Specify the parent ID to get the child categories of this parent category.
$sub_mark
– Optional. Mark that will append at the beginning of the child category name.
query("SELECT * FROM categories WHERE parent_id = $parent_id ORDER BY name ASC");
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
echo ''.$sub_mark.$row['name'].'';
categoryTree($row['id'], $sub_mark.'---');
}
}
}
Category Subcategory Dropdown in PHP
Use categoryTree()
function to build dynamic categories tree dropdown in PHP with MySQL.
Are you want to get implementation help, or modify or extend the functionality of this script?Submit paid service request
注意:本文来自CodexWorld。本站无法对本文内容的真实性、完整性、及时性、原创性提供任何保证,请您自行验证核实并承担相关的风险与后果!
CoLaBug.com遵循[CC BY-SA 4.0]分享并保持客观立场,本站不承担此类作品侵权行为的直接责任及连带责任。您有版权、意见、投诉等问题,请通过[eMail]联系我们处理,如需商业授权请联系原作者/原网站。