Building Dynamic Treeview for Menu or Category with PHP and MySQL

Apr 25, 2024 | PHP jQuery MySql Bootstrap Javascript


Output

Hello Dev,

If you're seeking a tutorial on crafting a Building Dynamic Treeview for Menu or Category with PHP and MySQL for menus or categories using PHP and MySQL, you've come to the right place. In this walkthrough, we'll systematically construct a dynamic tree view sourced from a database in PHP.

To create a treeview within your website application, it's advisable to utilize the Bootstrap Treeview plugin. This plugin facilitates the display of menus in hierarchical treeview structures, seamlessly integrated with PHP. In our example, we'll begin by creating an 'item' table with fields such as 'id', 'name', and 'parent_id'. Subsequently, we'll develop an index.php file containing jQuery Ajax code for generating the Building Dynamic Treeview for Menu or Category with PHP and MySQL. Following that, we'll establish an Ajax file and implement the necessary database logic within it.

By following these steps, you'll soon be able to observe the screen as depicted below.

Creating a Building Dynamic Treeview for Menu or Category with PHP and MySQL for menus or categories using PHP and MySQL involves several steps, including setting up your database, creating the HTML structure, and using JavaScript (with jQuery and AJAX) to dynamically load and display the treeview. Here's a step-by-step guide to help you achieve this:

Step 1: Database Setup

First, you need to create a table in your MySQL database to store your menu items. This table will have at least three columns: id, name, and parent_id. The parent_id column will be used to establish the hierarchical relationship between menu items.

CREATE TABLE `items` (
 `id` INT AUTO_INCREMENT PRIMARY KEY,
 `name` VARCHAR(255) NOT NULL,
 `parent_id` INT DEFAULT NULL,
 FOREIGN KEY (`parent_id`) REFERENCES `items`(`id`)
);
Step 2: HTML Structure

Create an index.php file for your webpage. This file will contain the HTML structure for your treeview. You can use Bootstrap for styling and layout.

Read Also: Using IF Condition in Laravel Select Query with MySQL CASE WHEN
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Building Dynamic Treeview for Menu or Category with PHP and MySQL -- ITErrorSolution.com</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
    <h1>Building Dynamic Treeview for Menu or Category with PHP and MySQL -- ITErrorSolution.com</h1>
    <div id="treeview"></div>

    <script src="script.js"></script>
</body>
</html>
Step 3: jQuery and AJAX for Dynamic Loading

Create a script.js file. This file will contain the jQuery and AJAX code to dynamically load and display the treeview.

$(document).ready(function() {
    loadTreeview();
});

function loadTreeview() {
    $.ajax({
        url: 'ajax.php',
        type: 'GET',
        dataType: 'json',
        success: function(data) {
            var treeview = '<ul>';
            $.each(data, function(i, item) {
                treeview += '<li>' + item.name;
                if (item.children.length > 0) {
                    treeview += loadTreeview(item.children);
                }
                treeview += '</li>';
            });
            treeview += '</ul>';
            $('#treeview').html(treeview);
        }
    });
}
Step 4: AJAX File for Database Logic

Create an ajax.php file. This file will handle the AJAX request, fetch data from the database, and return it in a format that can be used to build the treeview.

Read Also: MySQL Query for Data Between Two Dates
>?php
header('Content-Type: application/json');

// Database connection
$host = 'localhost';
$db   = 'your_database';
$user = 'your_username';
$pass = 'your_password';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);

// Fetch data from the database
$sql = "SELECT * FROM items WHERE parent_id IS NULL";
$stmt = $pdo->query($sql);
$items = $stmt->fetchAll();

// Recursive function to build the treeview structure
function buildTree($items, $parentId = null) {
    $tree = [];
    foreach ($items as $item) {
        if ($item['parent_id'] == $parentId) {
            $children = buildTree($items, $item['id']);
            $tree[] = ['id' => $item['id'], 'name' => $item['name'], 'children' => $children];
        }
    }
    return $tree;
}

// Build the treeview structure
$treeview = buildTree($items);

// Return the treeview structure as JSON
echo json_encode($treeview);
?>
Step 5: Viewing the Treeview

After completing the above steps, you should be able to view the Building Dynamic Treeview for Menu or Category with PHP and MySQL on your webpage. The treeview will be populated with data from your items table, displaying the hierarchical structure of menu items or categories.

This guide provides a basic setup for creating a Building Dynamic Treeview for Menu or Category with PHP and MySQL using PHP, MySQL, jQuery, and AJAX. You can further customize the appearance and functionality of the treeview using Bootstrap and additional JavaScript as needed.

Thank you for your encouragement! If you have any questions or need further assistance, feel free to ask. I'm here to help!



Tags :
#PHP
#jQuery
#MySql
#Bootstrap
#Javascript
ItErrorSolution.com

ItErrorSolution.com

"Hey there! I'm a full-stack developer and proud owner of ItErrorSolution.com, based right here in India. I love nothing more than sharing handy tips and tricks with my fellow developers through easy-to-follow tutorials. When it comes to coding, I'm all about PHP, Laravel, Angular, Vue, Node, JavaScript, jQuery, CodeIgniter, and Bootstrap – been hooked on them forever! I'm all about putting in the work and staying committed. Ready to join me on this journey to coding?"