Virajsinh

Multi Level Nested Category System in Codeigniter and MySql

Jul 15th, 2020
58
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Ref : https://www.myprogrammingtutorials.com/multi-level-nested-category-system-codeigniter-mysql.html
  2.  
  3. CREATE TABLE `categories` (
  4.   `cat_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  5.   `cat_name` varchar(50) COLLATE latin1_general_ci NOT NULL,
  6.   `parent_id` int(10) unsigned NOT NULL DEFAULT '0',
  7.   PRIMARY KEY (`cat_id`)
  8. ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
  9.  
  10. Model Function
  11.  
  12. public function get_categories(){
  13.  
  14.         $this->db->select('*');
  15.         $this->db->from('categories');
  16.         $this->db->where('parent_id', 0);
  17.  
  18.         $parent = $this->db->get();
  19.        
  20.         $categories = $parent->result();
  21.         $i=0;
  22.         foreach($categories as $p_cat){
  23.  
  24.             $categories[$i]->sub = $this->sub_categories($p_cat->cat_id);
  25.             $i++;
  26.         }
  27.         return $categories;
  28.     }
  29.  
  30.     public function sub_categories($id){
  31.  
  32.         $this->db->select('*');
  33.         $this->db->from('categories');
  34.         $this->db->where('parent_id', $id);
  35.  
  36.         $child = $this->db->get();
  37.         $categories = $child->result();
  38.         $i=0;
  39.         foreach($categories as $p_cat){
  40.  
  41.             $categories[$i]->sub = $this->sub_categories($p_cat->cat_id);
  42.             $i++;
  43.         }
  44.         return $categories;      
  45.     }
RAW Paste Data