Unlimited multilevel category list with PHP/MySQL

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mukherjiikunal
Forum Newbie
Posts: 3
Joined: Mon Dec 01, 2008 1:34 am

Unlimited multilevel category list with PHP/MySQL

Post by mukherjiikunal »

I have a table with the following structure:

cat_id (pk)
parent_cat_id
cat_desc

With the above mentioned struct we can go for a unlimited multilevel category list. This is applicable for either a ecomm, knowledge base, faq etc kinda site.

I know I have to use recursive function to get this done like the following:

Category 1
- sub cat 1
-- sub sub cat 1
-- sub sub cat 2
- sub cat 2
-- sub sub cat 3
Category 2
- sub cat 3
-- sub sub cat 4
-- sub sub cat 5

Please help me out with the idea/concept or example code re how to do this.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Unlimited multilevel category list with PHP/MySQL

Post by requinix »

  1. Get list of children with a specific parent
  2. For each child (assuming there are any)
    1. Do what you want with it (like, display it)
    2. Repeat step 1
mukherjiikunal
Forum Newbie
Posts: 3
Joined: Mon Dec 01, 2008 1:34 am

Re: Unlimited multilevel category list with PHP/MySQL

Post by mukherjiikunal »

I know the concept already. Would appreciate some sample code please!
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Unlimited multilevel category list with PHP/MySQL

Post by requinix »

Well then, let's see what I can come up with.

Code: Select all

function recursive($num, $indent = "") {
  1. Get list of children with a specific parent

    Code: Select all

    $children = mysql_query("SELECT num, name FROM table WHERE parent=$num");
  2. For each child (assuming there are any)

    Code: Select all

    while ($child = mysql_fetch_array($children)) {
    1. Do what you want with it (like, display it)

      Code: Select all

      echo $indent, " ", $child["name"], "<br/>\n";
    2. Repeat step 1

      Code: Select all

      recursive($child["num"], "--$indent");

    Code: Select all

    }

Code: Select all

}
mukherjiikunal
Forum Newbie
Posts: 3
Joined: Mon Dec 01, 2008 1:34 am

Re: Unlimited multilevel category list with PHP/MySQL

Post by mukherjiikunal »

Thanks a lot for your kind help. Will try the code and revert back.

Many thanks. :P
Post Reply