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
https://forums.phpfreaks.com/topic/237479-unlimited-sub-categories/
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.

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?

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.

Archived

This topic is now archived and is closed to further replies.

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