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
PHP Code:
$sql = mysql_query("SELECT * FROM " . TABLE_PREFIX . "categorytable ORDER BY CatRoot, CatParent");
while ($data = mysql_fetch_array($sql))
{
echo $data['CatName'] . "<br />";
}