@herminia_bruen
To create a tree-view category and subcategory in PHP and MySQL, you can follow these steps:
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 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 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(); ?> |
Note: This is a basic example, and you can customize it further by adding CSS and JavaScript to enhance the user experience.