Hello, today we are going to discuss on multi level category system in CodeIgniter which is a very common and essential module or feature of any e-commerce websites or any website.
Creating nested category system is not as easy as you think, but it is not impossible too. Here I am going to deliver full step by step tutorial on how you can create such kind of module using Codeigniter & MySql.
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.
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
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
public function categories(){
$this->load->model('model_categories');
$data = $this->model_categories->get_categories();
print_r($data);
}
if you are done with everything right as I mentioned in this brief tutorial, then after running the controller’s “categories()” function should produce the following result-
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.
If you find this article helpful please don’t get shy to share this article with your friends.
You may also like
- Split Unordered List Into Multiple Columns using CSS3 Property
- Track User’s Real IP Address
- Resize Image Without Stretching in Codeigniter
The post Multi Level Nested Category System in Codeigniter and MySql appeared first on My Programming Tutorials.