How to create Multi Level Category System in Codeigniter
This module is based on the recursive function concept. So let’s get started to develop multi level nested category system, carefully read below steps mentioned.
I am assuming that you are familiar with CodeIgniter’s MVC structure, so I’m not going to explain what model and controller in CI are.
1. create the database structure for categories
table and insert all the data as shown in below image
SQL code for categories
table, open SQL tab in PhpMyAdmin and run below code.
1 2 3 4 5 6 |
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; |
2. creating model functions
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 |
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; } |
3. creating controller function
1 2 3 4 5 6 7 |
public function categories(){ $this->load->model('model_categories'); $data = $this->model_categories->get_categories(); print_r($data); } |
in controller “categories()” function the variable $data
stores all the categories available in your categories table. As you can see $data
is an array, you can easily parse this array into any multi level menu item or lists.