Jump to content

unlimited sub-categories


UnknownPlayer

Recommended Posts

How can i make unlimited sub categories when i have this mysql fields: id, name, parent

 

 

$query = "SELECT * FROM cats";
$result = mysql_query($query);
while ($var = mysql_fetch_array($result)) {
  echo $var['name'];
  // now i need here some code for sub cats, but sub cat in subcat 
}

 

Can someone help me?

Link to comment
Share on other sites

The right approach depends on what you are doing.  Are you trying to display the entire category tree in a single page?  If so you will need recursion.  A good start would be to write a function called "get_subcats($id)" which recursively calls itself to get subcats of subcats.

Link to comment
Share on other sites

The code is simpler if you use multiple queries.  First make a function:

 

get_subcats($parent) {
  $query = "SELECT * FROM cats WHERE parent = '" . mysql_real_escape_string($parent) . "'";
  $result = mysql_query($query) or die("Error in $query: " . mysql_error());
  while ($var = mysql_fetch_array($result)) {
    echo $var['name'];
    get_subcats($var['id']);
  }  
}

 

I'm assuming your parent column is an id number.  Also the exact code depends on what value your top level nodes have for the parent column - is this null, 0 or some other value?

Link to comment
Share on other sites

Last week I was looking for a function that will return a tree structure of categories and unlimited subcategories, from a table with just 3 basic fields: id, category & parent_category.

This is the most simple code (very clever) that I found and it works fine. Test it and you'll see that you can have unlimited subcategories.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.