PDA

View Full Version : Unlimited Category Tree - Need Help


roosevelt
05-21-2006, 12:36 AM
For a while I've been trying to make this system and so far it goes up to one level. I am pretty sure there's a way to display unlimited category levels but that's what I just don't know. Anyways I will not post the actual source code but the concept should be enough for a more advanced PHP programmer.

Table
- CatId
- CatName
- CatParent

Example
CatId CatName CatParent (or subof)
1 Man 0
2 Woman 0
3 Boy 1
4 Girl 2
5 Baby Girl 4
6 Baby Boy 3

$sql = mysql_query("SELECT * FROM categorytable WHERE CatParent = '0'");
while ($data = mysql_fetch_array($sql))
{
echo "{$data['CatName']}<br />";
$sql2 = mysql_query("SELECT * FROM categorytable WHERE CatParent = '".$data['CatId']."'");
echo "- {$data2['CatName']}<br />";
}

My little while loop produces this:
Man
- Boy
Woman
- Girl

So if I wish to display Baby Girl category under Girl I will need another loop just under $sql2. Now the problem is I don't really know how deep the user will create his categories. So what is the trick to make unlimited categories?

Thanks a bunch in advance!!

hambil
05-21-2006, 04:08 PM
You need to add a CatRoot, then you can get it all in one query.

Table
- CatId
- CatName
- CatParent
- CatRoot

Example
CatId CatName CatParent (or subof)
1 Man 0 1
2 Woman 0 2
3 Boy 1 1
4 Girl 2 2
5 Baby Girl 4 2
6 Baby Boy 3 1


$sql = mysql_query("SELECT * FROM " . TABLE_PREFIX . "categorytable ORDER BY CatRoot, CatParent");
while ($data = mysql_fetch_array($sql))
{
echo $data['CatName'] . "<br />";
}