Saturday, 18 April 2015

Build Multi Level Category Using PHP & Mysql

In this tutorial we will create a multi-level nested category menu using PHP and mysql, by calling a recursive function, we can display infinite level of categories and subcategories on the fly, for a drop down box that might look like the following image.

Build Multi Level Category Using PHP & Mysql

Following is the PHP code snippet to build multi-level category using mysql :

Database Structure : 

You will need to create a table 'category' with 3 columns as follows : 

category_id : Primary key for the table.
category_name : Name of the category(level) that will be displayed in the drop down.
parent_id : It is the parent to corresponding category_id. For root category parent_id is 0.

PHP Code :


//Call Function

$cat_query = "SELECT category_id, category_name, parent_id FROM category ORDER BY parent_id, category_id";

//Execute the above mysql query an apply mysql_fetch_array() logic to get a multidimensional array.
$results = manual_query($cat_query);

foreach ($results as $result) {
    $category['categories'][$result['category_id']] = $result;
    $category['parent_cats'][$result['parent_id']][] = $result['category_id'];

$data[‘category’] = buildCategory(0, $category);

//Function Code

function buildCategory($parent, $category) {
    $html = "";
    if (isset($category['parent_cats'][$parent])) {
        $html .= "<ul>\n";
        foreach ($category['parent_cats'][$parent] as $cat_id) {
            if (!isset($category['parent_cats'][$cat_id])) {
                $html .= "<li>\n <a href = '” . site_url(‘home/category?category_id=’ . base64_encode(‘vikas’ . $cat_id)) . “‘>” . $category['categories'][$cat_id]['category_name'] . “</a>\n</li> \n";
            if (isset($category[‘parent_cats’][$cat_id])) {
            $html .= "<li>\n  <a href='” . site_url(‘home/category?category_id=’ . base64_encode(‘vikas’ . $cat_id)) . “‘>” . $category['categories'][$cat_id][‘category_name’] . “<i class = ’fa fa-angle-down’></i></a> \n";
                $html .= buildCategory($cat_id, $category);
                $html .= "</li> \n";
        $html .= “</ul> \n”;
    return $html;

Please leave your comment if you have any queries.

No comments:

Post a Comment