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

Prerequisites

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` */

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;

Step 4. Dump some data into database table – category

/*Data for the 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);

Step 5. 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 */

Step 6. 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 */

Step 7. 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>

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.

Tags:

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

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 *