-3

I write this recursive function, but it’s not working. I am not able to find the mistake. It’s not returning anything. But if I write an "echo" on the else statement, it’s printing perfectly.

function find_parent($referralid, $leg)
{
    $query = "SELECT memberid FROM memberdetails where parentid='" . $referralid . "'  and leg='" . $leg . "'";
    $result = mysql_query($query);
    if (mysql_num_rows($result) == 0)
        return $referralid;
    else
    {
        while($row = mysql_fetch_array($result))
        {
            find_parent($row[0], $leg);
        }
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sourav Sarkar
  • 292
  • 3
  • 20
  • Your code is open to [SQL injection](https://stackoverflow.com/q/332365/2469308) related attacks. Please learn to use [Prepared Statements](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Madhur Bhaiya Nov 03 '18 at 18:31
  • 3
    Please stop using **mysql_** extension. It has been removed completely from PHP 7. Consider using **mysqli_** or **PDO** extension instead. – Madhur Bhaiya Nov 03 '18 at 18:32
  • 1
    @MadhurBhaiya except if it's not, e.g. none of the arguments are related to user input. Of course it is always best to use prepared statements. – Vivick Nov 03 '18 at 18:33
  • 2
    @Vivick In this particular case, there is an additional benefit of preparing the statement only once, and reusing it by changing parameters. This will give some performance benefit, as MySQL server won't have to interpret same query again and again. – Madhur Bhaiya Nov 03 '18 at 18:37

1 Answers1

3

When you have recursion, you need to pass the value back as well, otherwise the value isn't propagated back up. So the line which is...

find_parent($row[0],$leg);

needs to be

return find_parent($row[0],$leg);

This is assuming that you will only ever get 1 row as a parent.

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55