-2

Please friends, I need help for my code.

My searchParent function always returns NULL when it executes the self:: more than once

class Search {
    public function listParents() {
        $sql = "SELECT id FROM parents";
        return pg_query($sql);
    }

    public function searchParent($id) {
        $parents= $this->listParents($con);
        while ($r = pg_fetch_array($parent)){
            if ($id === $r['id_parent']){
                return $id;
            } 
        }
        $sql = "SELECT id_parent FROM parent WHERE id_parent = $id";
        $query = pg_query($sql);
        $result = pg_fetch_array($query);

        self::searchParent($result['id_parent']);
    }
}

My call, assuming there is the number 230 in the parent table

$id = $search->searchParent(230);
dWinder
  • 11,597
  • 3
  • 24
  • 39
misterxis
  • 61
  • 1
  • 8
  • as it is recursive so it always it calls itself, and at a time the id_parent becomes null or zero, so it will return null to you – RAUSHAN KUMAR Aug 28 '18 at 05:28

2 Answers2

3

You need to bobble the return value of your function.

Before calling the self::searchParent you should add return statement:

return self::searchParent($result['id_parent']);
dWinder
  • 11,597
  • 3
  • 24
  • 39
0

You can optimize the code by using count and left join:

 class Search
{

    public function searchParent($id) {
         $sql = "SELECT count(*) as cnt 
                                FROM 
                                     parents LEFT JOIN parent on parent.id_parent = parents.id 
                                WHERE 
                                      parents.id = $id";
         $query = pg_query($sql);
         $result = pg_fetch_array($query);

         return empty($result['cnt']) ? null : $id; 
    }

}
Nisarg
  • 1,631
  • 6
  • 19
  • 31