Multi Level Category Menu PHP MySQL Source Code

Multi Level Category Menu PHP MySQL Source Code will make a multi-level stacked category menu using PHP and MySQL database, by contacting a recursive function, we can show unlimited degree of groups and subcategories on the fly.

Multi Level Category Menu PHP MySQL Source Code Database Structure :

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

Multi Level Category Menu PHP MySQL Source Code

<?php

//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;
}
?>

Comments

comments

View all contributions by

0 comments… add one