How To Create A Dynamic Menu Using PHP and MySQL
![](https://bestwebteacher.com/wp-content/uploads/2024/07/Dynamic-Menu.jpg)
what is Dynamic Menus
Dynamic menus are menus that are generated dynamically based on data stored in a database, such as MySQL. Unlike static menus, which are hardcoded into the website’s HTML, dynamic menus pull information from the database, allowing for easier updates and changes.
Part 1: Setting Up the Environment
- Install AMP or XAMPP Stack: Set up Apache, MySQL, and PHP on your local machine.
- Bootstrap Installation: Download Bootstrap or link to its CDN in your project.
Part 2: Database Setup
- Create Database and Tables: Design tables to store menu items and their attributes.
- Menu Table: Stores menu names and IDs.
- Menu Items Table: Stores individual menu items with their associated URLs and parent IDs.
Part 3: PHP Scripting
- Connect to MySQL Database: Use PHP’s PDO or MySQLi to establish a connection to the MySQL database.
- Retrieve Menu Items: Query the database to fetch menu items dynamically.
- Generate HTML Markup: Loop through retrieved menu items to generate HTML for the menu using Bootstrap’s navigation components.
Part 4: Bootstrap Styling
- Implement Navbar: Use Bootstrap’s Navbar component to structure the menu.
- Responsive Design: Ensure the menu adapts to different screen sizes using Bootstrap’s responsive utilities.
Part 5: Enhancing Functionality
- Active Menu Highlighting: Highlight the active menu item based on the current page.
- Dropdown Menus: Implement dropdown menus for sub-items using Bootstrap’s Dropdown component.
- Mobile Menu Toggle: Add a mobile-friendly menu toggle using Bootstrap’s Collapse component.
Create Database and Tables
- Open your MySQL client (e.g., phpMyAdmin) and create a new database named
dynamic_menu
. - Create two tables:
menus
andmenu_items
using the following SQL queries:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
-- Create 'menus' table CREATE TABLE menus ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50) NOT NULL ); -- Create 'menu_items' table CREATE TABLE menu_items ( id INT AUTO_INCREMENT PRIMARY KEY, menu_id INT, parent_id INT DEFAULT 0, name VARCHAR(50) NOT NULL, url VARCHAR(255) NOT NULL, FOREIGN KEY (menu_id) REFERENCES menus(id) ); |
Connect to MySQL Database
- Create a PHP file named
db_connect.php
to establish a connection to the MySQL database:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php $host = 'localhost'; $db_name = 'dynamic_menu'; $username = 'root'; $password = ''; try { $conn = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo 'Connection Error: ' . $e->getMessage(); die(); } ?> |
Retrieve Menu Items
- Create a PHP script to fetch menu items from the database. Let’s name it
get_menus.php
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php // Include database connection require_once 'db_connect.php'; // Query to fetch menus $query = "SELECT * FROM menus"; $stmt = $conn->prepare($query); $stmt->execute(); $menus = $stmt->fetchAll(PDO::FETCH_ASSOC); // Query to fetch menu items $query = "SELECT * FROM menu_items"; $stmt = $conn->prepare($query); $stmt->execute(); $menu_items = $stmt->fetchAll(PDO::FETCH_ASSOC); ?> |
Generate HTML Markup
- Use Bootstrap’s Navbar component to generate HTML markup for the dynamic menu in your
index.php
orheader.php
file:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="#">Dynamic Menu</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <?php foreach ($menus as $menu): ?> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown<?= $menu['id'] ?>" role="button" data-bs-toggle="dropdown" aria-expanded="false"> <?= $menu['name'] ?> </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown<?= $menu['id'] ?>"> <?php foreach ($menu_items as $item): ?> <?php if ($item['menu_id'] == $menu['id']): ?> <?php if ($item['parent_id'] == 0): ?> <li><a class="dropdown-item" href="<?= $item['url'] ?>"><?= $item['name'] ?></a></li> <?php else: ?> <li><a class="dropdown-item" href="<?= $item['url'] ?>"><?= $item['name'] ?></a></li> <?php endif; ?> <?php endif; ?> <?php endforeach; ?> </ul> </li> <?php endforeach; ?> </ul> </div> </div> </nav> |
dynamic menu using PHP, MySQL, and Bootstrap, all on a single page (index.php
):
SQL INSERT
Statements
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
-- Create 'menus' table CREATE TABLE menus ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50) NOT NULL ); -- Create 'menu_items' table CREATE TABLE menu_items ( id INT AUTO_INCREMENT PRIMARY KEY, menu_id INT, parent_id INT DEFAULT 0, name VARCHAR(50) NOT NULL, url VARCHAR(255) NOT NULL, FOREIGN KEY (menu_id) REFERENCES menus(id) ); INSERT INTO menus (name) VALUES ('Main Menu'), ('Footer Menu'); INSERT INTO menu_items (menu_id, parent_id, name, url) VALUES (1, 0, 'Home', '/'), (1, 0, 'About Us', '/about'), (1, 0, 'Services', '/services'), (1, 0, 'Products', '/products'), (1, 0, 'Contact Us', '/contact'), (2, 0, 'Privacy Policy', '/privacy-policy'), (2, 0, 'Terms of Service', '/terms-of-service'); |
index.php
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dynamic Menu using PHP, MySQL, Bootstrap</title> <!-- Bootstrap CSS --> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <?php // Database connection $host = 'localhost'; $db_name = 'dynamic_menu'; $username = 'root'; $password = ''; try { $conn = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo 'Connection Error: ' . $e->getMessage(); die(); } // Fetch menus $query_menus = "SELECT * FROM menus"; $stmt_menus = $conn->prepare($query_menus); $stmt_menus->execute(); $menus = $stmt_menus->fetchAll(PDO::FETCH_ASSOC); // Fetch menu items $query_items = "SELECT * FROM menu_items"; $stmt_items = $conn->prepare($query_items); $stmt_items->execute(); $menu_items = $stmt_items->fetchAll(PDO::FETCH_ASSOC); ?> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container"> <a class="navbar-brand" href="#">Dynamic Menu</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <?php foreach ($menus as $menu): ?> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown<?= $menu['id'] ?>" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <?= $menu['name'] ?> </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown<?= $menu['id'] ?>"> <?php foreach ($menu_items as $item): ?> <?php if ($item['menu_id'] == $menu['id']): ?> <?php if ($item['parent_id'] == 0): ?> <a class="dropdown-item" href="<?= $item['url'] ?>"><?= $item['name'] ?></a> <?php else: ?> <div class="dropdown-divider"></div> <a class="dropdown-item" href="<?= $item['url'] ?>"><?= $item['name'] ?></a> <?php endif; ?> <?php endif; ?> <?php endforeach; ?> </div> </li> <?php endforeach; ?> </ul> </div> </div> </nav> <!-- Bootstrap JS and dependencies --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@1.16.1/dist/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> </body> </html> |