Introduction

Here we will see how to create infinite multi-level nested categories with Codeigniter and MySQL. In my previous tutorial Infinite dynamic Multi-level nested category with PHP and MySQL , I wrote how to build a nested multilevel categories. So I am again going to write the same tutorial but this time with Codeigniter 3 framework.

Please follow below steps to find this example working

Prerequisites

Codeigniter 3.1.10, PHP 7.0.15, MySQL 5.5, Apache 2.4

Example with Source Code

Directory Structure

A typical directory structure for the project would be as shown below. Here assests directory will contain static resources like css, js, images.

nested categories codeigniter

Final Result

nested categories codeigniter

Now we will see how it happens step by step.

Configuring Auto-load

Modify ci3/application/config/autoload.php file for auto-loading html, url, file, form and session. Auto-loading such things will be available throughout the application wherever you want to use and you don’t need to load again and again.

$autoload['helper'] = array('html', 'url', 'file', 'form');
$autoload['libraries'] = array('database');

Configuring Database

Go to location ci3/application/config/database.php file and change database parameter values for below parameters. Make sure to have your correct database name.

$db['default']['username'] = 'root'; //your database username
$db['default']['password'] = ''; //your database password
$db['default']['database'] = 'roytuts'; //your MySQL database name

Creating MySQL Table

Create a MySQL table – category in “roytuts” database.

USE `roytuts`;

/*Table structure for table `category` */

DROP TABLE IF EXISTS `category`;

CREATE TABLE `category` (
  `category_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `category_name` varchar(50) COLLATE latin1_general_ci NOT NULL,
  `category_link` varchar(255) COLLATE latin1_general_ci NOT NULL,
  `parent_id` int(10) unsigned NOT NULL DEFAULT '0',
  `sort_order` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`category_id`),
  UNIQUE KEY `unique` (`category_name`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;

Dumping Data

Dump some data into database table – category.

insert  into 
`category`(`category_id`,`category_name`,`category_link`,`parent_id`,`sort_order`) 
values 
(1,'Home','',0,0),
(2,'Tutorials','#',0,1),
(3,'Java','java',2,1),
(4,'Liferay','liferay',2,1),
(5,'Frameworks','#',0,2),
(6,'JSF','jsf',5,2),
(7,'Struts','struts',5,2),
(8,'Spring','spring',5,2),
(9,'Hibernate','hibernate',5,2),
(10,'Webservices','#',0,3),
(11,'REST','rest',10,3),
(12,'SOAP','soap',10,3),
(13,'Contact','contact',0,4),
(14,'About','about',0,5);

Creating Model Class

Create a model file categorymodel.php under ci3/application/models directory with the below source code.

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Description of categorymodel
 *
 * @author https://roytuts.com
 */
class CategoryModel extends CI_Model {

    private $category = 'category';

    function __construct() {
        
    }

    public function category_menu() {
        // Select all entries from the menu table
        $query = $this->db->query("select category_id, category_name, category_link,
            parent_id from " . $this->category . " order by parent_id, category_link");

        // Create a multidimensional array to contain a list of items and parents
        $cat = array(
            'items' => array(),
            'parents' => array()
        );
        // Builds the array lists with data from the menu table
        foreach ($query->result() as $cats) {
            // Creates entry into items array with current menu item id ie. $menu['items'][1]
            $cat['items'][$cats->category_id] = $cats;
            // Creates entry into parents array. Parents array contains a list of all items with children
            $cat['parents'][$cats->parent_id][] = $cats->category_id;
        }

        if ($cat) {
            $result = $this->build_category_menu(0, $cat);
            return $result;
        } else {
            return FALSE;
        }
    }

    // Menu builder function, parentId 0 is the root
    function build_category_menu($parent, $menu) {
        $html = "";
        if (isset($menu['parents'][$parent])) {
            $html .= "<ul>n";
            foreach ($menu['parents'][$parent] as $itemId) {
                if (!isset($menu['parents'][$itemId])) {
                    $html .= "<li>n<a href='" . base_url() . 'index.php/category/index/' . $menu['items'][$itemId]->category_link . "'><span>" . $menu['items'][$itemId]->category_name . "</span></a>n</li>n";
                }
                if (isset($menu['parents'][$itemId])) {
                    $html .= "<li>n<a class='parent' href='" . base_url() . 'index.php/category/index/' . $menu['items'][$itemId]->category_link . "'><span>" . $menu['items'][$itemId]->category_name . "</span></a>n";
                    $html .= $this->build_category_menu($itemId, $menu);
                    $html .= "</li>n";
                }
            }
            $html .= "</ul>n";
        }
        return $html;
    }

}

/* End of file categorymodel.php */
/* Location: ./application/models/categorymodel.php */

Creating Controller Class

Create a controller file category.php under ci3/application/controllers with the following source code.

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Description of category
 *
 * @author https://roytuts.com
 */
class Category extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('categorymodel', 'cat');
    }

    function index() {
        $data['categories'] = $this->cat->category_menu();
        $this->load->view('category', $data);
    }

}

/* End of file category.php */
/* Location: ./application/controllers/category.php */

Creating View

Create a view file category.php under ci3/application/views.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <?php
        echo $categories;
        ?>
    </body>
</html>

Configuring Route

Modify file ci3/application/config/routes.php file

$route['default_controller'] = 'category';

Testing the Application

If everything is fine then run the application by hitting the URL http://localhost/ci3/index.php. You will get the output in the browser as shown in the Final Result section above.

That’s all. Thanks for reading.

Tags:

1 thought on “Infinite dynamic Multi-level nested category with Codeigniter and MySQL

Leave a Reply

Your email address will not be published. Required fields are marked *