How To Create A Dynamic Menu Using PHP and MySQL

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

  1. Install AMP or XAMPP Stack: Set up Apache, MySQL, and PHP on your local machine.
  2. Bootstrap Installation: Download Bootstrap or link to its CDN in your project.

Part 2: Database Setup

  1. 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

  1. Connect to MySQL Database: Use PHP’s PDO or MySQLi to establish a connection to the MySQL database.
  2. Retrieve Menu Items: Query the database to fetch menu items dynamically.
  3. Generate HTML Markup: Loop through retrieved menu items to generate HTML for the menu using Bootstrap’s navigation components.

Part 4: Bootstrap Styling

  1. Implement Navbar: Use Bootstrap’s Navbar component to structure the menu.
  2. Responsive Design: Ensure the menu adapts to different screen sizes using Bootstrap’s responsive utilities.

Part 5: Enhancing Functionality

  1. Active Menu Highlighting: Highlight the active menu item based on the current page.
  2. Dropdown Menus: Implement dropdown menus for sub-items using Bootstrap’s Dropdown component.
  3. 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 and menu_items using the following SQL queries:

Connect to MySQL Database

  • Create a PHP file named db_connect.php to establish a connection to the MySQL database:

Retrieve Menu Items

  • Create a PHP script to fetch menu items from the database. Let’s name it get_menus.php

Generate HTML Markup

  • Use Bootstrap’s Navbar component to generate HTML markup for the dynamic menu in your index.php or header.php file:

dynamic menu using PHP, MySQL, and Bootstrap, all on a single page (index.php):

SQL INSERT Statements

 

index.php

Download Source Code   View Demo

You may also like...

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments