Date Posted: 10-09-2018

In this Post we will explain create dynamic menu from database using codeigniter.

We assuming that you are familiar with CodeIgniter’s MVC structure, so We did not going to explain what model and controller in CI are.

Step 1: Please execute the following command and create the table.

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;

Step 2: Create the new controller file and paste the following code.

<?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(){

        $this->load->model('Dashboard_model');
      $data = $this->Dashboard_model->get_categories();

      print_r($data);
        }

}

Step 2: Create the new model file and paste the following code.

<?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;       
    }

}

 

2 thoughts on “Create dynamic menu from database using codeigniter”

Leave a Reply