Create Dynamic Multi-Level Menu from Database Using CodeIgniter

Post Date: September 10, 2018
Last Updated: September 22, 2026

 Introduction

Dynamic menus are a common requirement in modern web applications. Instead of hardcoding menu items, storing menu data in a database allows administrators to add, update, or remove menu entries without modifying application code.

In this tutorial, we will create a dynamic multi-level menu (parent and child categories) using CodeIgniter and MySQL. The menu structure will be generated recursively from a database table, making it suitable for category trees, navigation menus, product catalogs, and content management systems.

By the end of this guide, you will learn how to:

  • Create a category table in MySQL
  • Fetch parent and child categories dynamically
  • Build recursive menu structures
  • Organize code using CodeIgniter’s MVC architecture
  • Generate unlimited menu levels

Prerequisites

Before starting, ensure you have:

  • CodeIgniter installed and configured
  • MySQL database configured
  • Basic knowledge of:
    • PHP
    • MySQL
    • CodeIgniter MVC structure
  • Database connectivity configured in application/config/database.php

How It Works

The application follows this process:


Database Structure

Step 1: Create Categories Table

Execute the following SQL query:

CREATE TABLE `categories` (
  `cat_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `cat_name` varchar(50) COLLATE latin1_general_ci NOT NULL,
  `parent_id` int(10) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`cat_id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;

Table Explanation

ColumnDescription
cat_idUnique category ID
cat_nameCategory name
parent_idParent category reference
0Indicates a root category

Example Data

cat_idcat_nameparent_id
1Electronics0
2Mobile Phones1
3Android Phones2
4iPhones2
5Laptops1

Resulting Structure:

Electronics
├── Mobile Phones
│   ├── Android Phones
│   └── iPhones
└── Laptops

Step 2: Create Controller

Create a new controller file:

application/controllers/Dashboard.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Dashboard extends MY_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('Dashboard_model');
    }

    public function index()
    {
        $data['title'] = "Dashboard";
        $data['page_name'] = "Dashboard";

        $this->include_view('dashboard', $data);
    }

    public function categories()
    {
        $data = $this->Dashboard_model->get_categories();

        echo "<pre>";
        print_r($data);
        echo "</pre>";
    }
}

Controller Responsibilities

  • Loads the model
  • Requests category data
  • Sends data to views
  • Displays hierarchical category structure

Step 3: Create Model

Create a model file:

application/models/Dashboard_model.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Dashboard_model extends CI_Model {

    public function get_categories()
    {
        $this->db->select('*');
        $this->db->from('categories');
        $this->db->where('parent_id', 0);

        $parent = $this->db->get();

        $categories = $parent->result();

        $i = 0;

        foreach ($categories as $p_cat)
        {
            $categories[$i]->sub = $this->sub_categories($p_cat->cat_id);
            $i++;
        }

        return $categories;
    }

    public function sub_categories($id)
    {
        $this->db->select('*');
        $this->db->from('categories');
        $this->db->where('parent_id', $id);

        $child = $this->db->get();

        $categories = $child->result();

        $i = 0;

        foreach ($categories as $p_cat)
        {
            $categories[$i]->sub = $this->sub_categories($p_cat->cat_id);
            $i++;
        }

        return $categories;
    }
}

Understanding the Recursive Function

The key feature of this implementation is recursion.

What Happens?

  1. Fetch all parent categories.
  2. For each parent category:
    • Search for child categories.
  3. If child categories exist:
    • Search for their children.
  4. Continue until no more child categories are found.
  5. Return the complete nested structure.

Recursive Flow

Parent Category
      │
      ▼
Find Child Categories
      │
      ▼
Child Found?
 ├─ No → Return
 └─ Yes
       │
       ▼
Call Function Again
       │
       ▼
Find Next Level Children

This approach supports unlimited menu depth.


Sample Output

Array
(
    [0] => stdClass Object
        (
            [cat_id] => 1
            [cat_name] => Electronics
            [parent_id] => 0
            [sub] => Array
                (
                    [0] => stdClass Object
                        (
                            [cat_id] => 2
                            [cat_name] => Mobile Phones
                            [parent_id] => 1
                        )
                )
        )
)

Benefits of Dynamic Menus

  • No hardcoded navigation
  • Easy administration
  • Unlimited category levels
  • Database-driven architecture
  • Suitable for eCommerce sites
  • Suitable for CMS platforms
  • Better scalability

Performance Considerations

For large category trees:

  • Add an index on parent_id
ALTER TABLE categories
ADD INDEX idx_parent_id(parent_id);
  • Implement caching
  • Use eager loading where possible
  • Limit recursion depth if required
  • Consider Nested Sets or Closure Tables for very large datasets

Conclusion

Creating a dynamic menu from a database in CodeIgniter is an effective way to build scalable and maintainable navigation systems. By using a recursive model function, you can generate multi-level category trees of any depth without hardcoding menu items.

This approach is ideal for:

  • eCommerce category navigation
  • CMS menus
  • Product hierarchies
  • Knowledge base structures
  • Blog category systems

With proper indexing and caching, this solution can efficiently handle both small and large category structures while keeping your application flexible and easy to manage.


Frequently Asked Questions (FAQ)

1. Can this support unlimited menu levels?

Yes. The recursive function allows unlimited parent-child relationships.

2. What does parent_id = 0 mean?

It identifies root-level categories.

3. Can I display the data as a Bootstrap dropdown menu?

Yes. The returned array can be looped through recursively in a view to generate Bootstrap dropdown navigation.



Talk to our experts

Have a technology challenge or looking for the right solution for your business? Our team can help you with cloud, DevOps, development, infrastructure, design, and more. Feel free to reach out to our experts here.

admin

Our team has expertise across software and web development, WordPress, e-commerce, mobile applications, UI/UX, cloud and infrastructure, DevOps, CI/CD, API integration, security, testing, automation, and technical support. The team also works with AI-based software solutions, LLMs, AI workflows, AI agents, and intelligent application development to help businesses automate processes and build smarter digital solutions. We focus on developing, deploying, maintaining, and optimising secure, scalable, and reliable technology solutions while helping businesses adopt modern technologies and drive digital transformation.

2 thoughts on “Create Dynamic Multi-Level Menu from Database Using CodeIgniter”

Leave a Comment

Scroll to Top