0

So every member has an intro_id, which stands for the userid of the guy who referred the member. If member 2 was referred by member 1, member 2s intro_id would be 1.

I am basically trying to "count" every ref, multiple levels deep. First level are direct referrals, second level are referrals referred by the first level refs.

Code so far:

function countReferrals($userid, $i){
    if($userid=='')
    {
       $userid=$_SESSION['member_id'];
    }
    if($i=='' || empty($i))
    {
       $i=0;
    }

    $query1 = new Bin_Query();
    $sql = "select member_id from members where intro_id='".$userid."'";
    $query1->executeQuery($sql);
    $level1Refs = $query1->records;

    foreach($level1Refs as $refer)
    {
       $i=$i+1;
       echo "<script>console.log( 'Debug Objects | countReferrals | \$i = ".$i." | \$refer[member_id] = ".$refer['member_id']."  ' );</script>";
       self::countReferrals($refer['member_id'], $i);
    }
}

This maximum output number ($i) is around 150. Sometimes 149, 146, ... First level referrals are 400+ and some in second level. So it's clearly stopping before it counts every ref, but why?

If I remove

self::countReferrals($refer['member_id'], $i);

It counts all level 1 refs. But I want refs from the other levels, too.

14
  • have You tried to extend memory limit from php.ini ? Commented Aug 12, 2017 at 21:47
  • 1
    Please indent your code. Commented Aug 12, 2017 at 21:50
  • 1
    And every question that includes SQL code like yours needs this comment: Your code is vulnerable to SQL injection attacks. Use prepared statements: stackoverflow.com/questions/60174/… Commented Aug 12, 2017 at 21:51
  • 1
    Thanks @Dawg. Sadly it means my guess was wrong. The different levels in the recursion probably don't modify each other. Maybe BeetleJuice is right and there are cycles in your referral system that lead to infinite recursion? Commented Aug 12, 2017 at 22:36
  • 1
    @Dawg Yes. Or longer chains like 1 referred 2 who referred 3 and 3 referred 1 again. Commented Aug 12, 2017 at 22:50

1 Answer 1

1

Your code runs in an endless loop (or at least until PHP cuts it off), because there is no restriction on when the recursive call is made. So when you see 149 or 150, it's likely because you have gone 148 or 149 levels deep and at the root function, you are still on the very first record.

If you're interested only in n levels of depth, provide n as a parameter, and increment it every time you make a recursive call. In the function, check if n > $maxLevels return immediately.

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

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.