How to tree view category subcategory in php & mysql?

by herminia_bruen , in category: PHP General , a year ago

How to tree view category subcategory in php & mysql?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by aubrey , 5 months ago

@herminia_bruen 

To create a tree-view category and subcategory in PHP and MySQL, you can follow these steps:

  1. Create a MySQL table to store the categories and subcategories. Below is an example of the table structure:
1
2
3
4
5
CREATE TABLE categories (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(50) NOT NULL,
    parent_id INT DEFAULT NULL
);


  1. Insert some sample data into the table. Here is an example:
1
2
3
4
5
6
INSERT INTO categories (name, parent_id) VALUES ('Fruits', NULL);
INSERT INTO categories (name, parent_id) VALUES ('Apples', 1);
INSERT INTO categories (name, parent_id) VALUES ('Oranges', 1);
INSERT INTO categories (name, parent_id) VALUES ('Vegetables', NULL);
INSERT INTO categories (name, parent_id) VALUES ('Carrots', 4);
INSERT INTO categories (name, parent_id) VALUES ('Tomatoes', 4);


  1. Create a PHP script to fetch the categories and subcategories from the database and display them in a tree-view format. Below is an example of the PHP script:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<?php

$connection = mysqli_connect('localhost', 'username', 'password', 'database');

function getCategories($parent_id = NULL, $level = 0) {
    global $connection;
    
    $query = "SELECT * FROM categories WHERE parent_id = " . $parent_id;
    $result = mysqli_query($connection, $query);
    
    while ($row = mysqli_fetch_assoc($result)) {
        echo str_repeat('-', $level) . $row['name'] . "<br>";
        
        getCategories($row['id'], $level + 1);
    }
}

getCategories();

?>


  1. Run the PHP script in a web browser, and you should see the categories and subcategories displayed in a tree-view format.


Note: This is a basic example, and you can customize it further by adding CSS and JavaScript to enhance the user experience.