Infinite dynamic Multi-level nested category with PHP and MySQL

I wanted to build the infinite level of categories and subcategories on the fly from a MySQL database. So I am going to give an example how to build a dynamic infinite level of nested categories.

You may read also Infinite dynamic Multi-level nested category with Codeigniter and MySQL


Create MySQL table

 

The table has following five columns
category_id – autoincremented positive int value, the primary key as well
category_name – name or level of the viewable category, the unique key
category_link – url for this category
parent_id – who is the parent of this category. For root category, the parent_id is 0.
sort_order – the order – what comes next

we have table so now we need some data into it.

 

infinite nested categories in php and mysql

Now fetch the result using the following query

 

infinite nested categories in php and mysql

The following logic retrieves the results from the category table and puts the results into a multidimensional array.
The $category contains two other arrays, categories holds every result from the category table query, the parent_cats array holds a list of all category ids that have children. Next we use a while statement to run through the sql results and assign row to the arrays. If the row parent id already exists in the parent_cats array it will be overwritten so there will only be one of each parent id listed.

 

Now build the category and subcategory function which will display the final results.

//category and subcategory builder function, parent 0 is the root

 

Display the result using the following example

 

Final output in the browser

infinite nested categories in php and mysql

You got the idea how to build a infinite level of category and subcategory. Now you can apply CSS or customization as per your needs.

Thanks for reading.

Soumitra

Software Professional, I am passionate to work on web/enterprise application. For more information please go to about me. You can follow on Twitter. You can be a friend on Facebook or Google Plus or Linkedin

3 thoughts on “Infinite dynamic Multi-level nested category with PHP and MySQL

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.