We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,601 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Help Breaking out of Infinate Loop

I have created a recursive function to get parent products of a product. I'm almost sure I'm nearly there, but need help snapping out of recursion.

The result I am looking for is something like:

Product 1 (id:1, parent:none)
--- Product 2 (id:2, parent:1)
--- --- Product 3 (id:3, parent:2)
--- --- Product 4 (id:4, parent:2)
--- Product 5 (id:5, parent:1)
--- --- Product 6 (id:6, parent:5)
--- --- Product 7 (id:7, parent:5)

My function is as follows:

function get_parents ($pid, $found = array()) {
    array_push ($found, $pid);

    $sql = "SELECT * FROM products WHERE child_id = '$pid'";
    $result = mysql_query($sql) or die ($sql);

    if(mysql_num_rows($result)){
        while($row = mysql_fetch_assoc($result)){
            $found[] = get_parents($row['pid'], $found);
        }
    }
    return $found;
}

I call it using a simple:

$parents = get_parents($pid);

The problem I am having is that when I run it, it creates an infinite loop, which doesn't break.

I think whats happening is there are 8 results from the first query and then it does another 8 queries and another 8 queries and so on until php crashes.

I have attached the result of my array in text file.

Any help would be seriously appreciated :-)

Attachments array.txt (51.48KB)
2
Contributors
1
Reply
4 Hours
Discussion Span
1 Year Ago
Last Updated
2
Views
hawx
Newbie Poster
8 posts since Mar 2011
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0

Hiiii,check that code:

function get_parents ($pid, $found = array()) {
    array_push ($found, $pid);

    $sql = "SELECT * FROM products WHERE child_id = '$pid'";
    $result = mysql_query($sql) or die ($sql);

    if(mysql_num_rows($result)>0){
        while($row = mysql_fetch_array($result)){
            $found[] = get_parents($row['pid'], $found);
        }
    }
    return $found;
}

%^^%Murtada%^^%

Morta
Light Poster
45 posts since Sep 2011
Reputation Points: 25
Solved Threads: 4
Skill Endorsements: 0

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0589 seconds using 2.69MB