Here is what I'm trying to do: - i need a function that when passed as an argument an ID (for a category of things) will provide all the subcategories and the sub-sub categories and sub-sub-sub..etc. - i was thinking to use a recursive function since i don't know the number of subcategories their sub-subcategories and so on so here is what i've tried to do so far
function categoryChild($id) {
$s = "SELECT * FROM PLD_CATEGORY WHERE PARENT_ID = $id";
$r = mysql_query($s);
if(mysql_num_rows($r) > 0) {
while($row = mysql_fetch_array($r))
echo $row['ID'].",".categoryChild($row['ID']);
}
else {
$row = mysql_fetch_array($r);
return $row['ID'];
}
}
If i use return instead of echo, i won't get the same result. I need some help in order to fix this or rewrite it from scratch
As this has been brought up by @Pawan Sharma, I thought that I might give some answer as well.
All given solutions suffer from common problem - they perform SQL query for each and every child. E.g., if there are 100 childs in 2nd level, then 100 queries will be done, while it can actually be done in single query by using
where parent_id in (<list_of_ids>)
.Sample DB:
Here's my solution:
With provided sample data, it does at most 5 queries, when called as
getTree(null)
(for all entries):When called as
getTree(4)
, 3 queries are performed: