Dynamic Category Subcategory Tree using PHP and MySQL

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.

<?php
// Database configuration
$dbHost     "localhost";
$dbUsername "root";
$dbPassword "root";
$dbName     "codexworld";

// Create database connection
$db = new mysqli($dbHost$dbUsername$dbPassword$dbName);

// Check connection
if ($db->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.
<?php
// Include the database configuration file
require 'dbConfig.php';

function 
categoryTree($parent_id 0$sub_mark ''){
    global 
$db;
    
$query $db->query("SELECT * FROM categories WHERE parent_id = $parent_id ORDER BY name ASC");
   
    if(
$query->num_rows 0){
        while(
$row $query->fetch_assoc()){
            echo 
'<option value="'.$row['id'].'">'.$sub_mark.$row['name'].'</option>';
            
categoryTree($row['id'], $sub_mark.'---');
        }
    }
}

Category Subcategory Dropdown in PHP

Use categoryTree() function to build dynamic categories tree dropdown in PHP with MySQL.

<select name="category">
    <?php categoryTree(); ?>
</select>

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

4 Comments

  1. Bharti Said...
  2. Mukesh Jakhar Said...
  3. Yasin Said...
  4. Vvivs Said...

Leave a reply

keyboard_double_arrow_up