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 have again written the same tutorial but this time with Codeigniter 3 framework.

Please follow below steps to find this example working


Netbeans 8.1
XAMPP in Windows
Codeigniter 3.0.6

Configure XAMPP and Netbeans

From Netbeans IDE go to Tools->Options. Click on PHP. Now on tab “General” browse the file for “PHP 5 Interpreter”. The php interpreter file generally placed inside the <physical drive in Windows OS>:xamppphpphp.exe

Configure Codeigniter and Netbeans

Create a new PHP project in Netbeans. Then remove the index.php file from the newly created project. Now copy the extracted files from Codeigniter 3.0.6 to the newly created project directory.

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 output in the browser

nested categories codeigniter

Now we will see how it happens step by step.

Step 1. Now modify <root directory>/application/config/autoload.php file for auto-loading html, url, file, form and session

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

$autoload['libraries'] = array('database');

Step 2. Go to location ci/application/config/database.php file and change database parameter values for below parameters

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

Step 3. Create a MySQL table in “roytuts” database

USE `roytuts`;

/*Table structure for table `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`)

Step 4. Dump some data into database table – category

/*Data for the table `category` */

insert  into 

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


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

 * Description of categorymodel
 * @author
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 */

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


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

 * Description of category
 * @author
class Category extends CI_Controller {

    function __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 */

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

<!DOCTYPE html>
        <meta charset="UTF-8">
        echo $categories;

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

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

Step 9. If everything is fine then run the application. You will get the output in the browser.

That’s all. Thanks for reading.


I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

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 *