Mohammad
Mohammad

Reputation: 179

While loop returns only first row value

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?

Upvotes: 0

Views: 1058

Answers (2)

Alexander
Alexander

Reputation: 809

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); 

Upvotes: 2

sg3s
sg3s

Reputation: 9567

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.

Upvotes: 2

Related Questions