0

For my tree category I use the below code, but there seems to be a problem, since it returns only the value of the 1st row:

<?php
function display_children($parent, $level) { 
    $result = mysql_query("SELECT * FROM `category` WHERE `parent`='$parent'"); 
    while ($row = mysql_fetch_array($result)) { 
        $title = $row['title'];
        $id = $row['id'];
        $results .= str_repeat('-> ',$level).$title;
        display_children($id, $level+1); 
    } 
    return $results;
}
display_children(0,0); 
?>

Any ideas what am I doing wrong and how to fix this?

1
  • Never ever put a query inside a loop, or even worse, inside a recursive function. There are 100 ways to do this better. Commented Nov 11, 2013 at 13:28

2 Answers 2

2

I see you're not doing anything with your recursive function call return in there. Specifically I think you mean to also add those results to the $results variable...

Try this:

<?php
function display_children($parent, $level) { 
    $result = mysql_query("SELECT * FROM `category` WHERE `parent`='$parent'"); 
    $results = '';
    while ($row = mysql_fetch_array($result)) { 
        $title = $row['title'];
        $id = $row['id'];
        $results .= str_repeat('-> ',$level).$title;
        $results .= display_children($id, $level+1); 
    } 
    return $results;
}
echo display_children(0,0); 
?>

Additionally I declared the $results variable to prevent notices.

Sign up to request clarification or add additional context in comments.

Comments

2

Result of your function is lost. Replace:

$results .= str_repeat('-> ',$level).$title;
display_children($id, $level+1);

To:

$results .= str_repeat('-> ',$level).$title."\n".display_children($id, $level+1); 

And at the end also display results:

echo display_children(0,0); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.