0

This is my table

parentID   id
1          0
1          2
3          4
2          3
4          5
5          6
6          7
7          8
8          9
9         10

This is my php code---->

 function countChildren($parentId) {

     $link=mysql_connect("localhost","root","");
     mysql_select_db("employee",$link);

     $sql = ("select id from relation where parentID='2'");
     $result=mysql_query($sql,$link);
     $count = mysql_num_rows($result);

     $userinfo = array();

     while ($row_user = mysql_fetch_assoc($result))
    {
       $userinfo[] = $row_user;
    }
    foreach($userinfo  as $userId) 
    {
       $count += countChildren($userId);
    }
return $count;

}

Now i want to count all the child nodes of a parent node using the above code but my code is give error like -->

Fatal error: Maximum function nesting level of '100' reached, aborting! in C:\wamp\www\Project\index.php on line 7

Sinto
  • 3,915
  • 11
  • 36
  • 70
Kamal Gayan
  • 371
  • 1
  • 3
  • 9

1 Answers1

-1

Just do the counting in the query and pass the parent_id as an input. Use prepared statements.

// ....

$stmt = $db->prepare("SELECT COUNT(*) childrenCount FROM relation WHERE parentID=?");
$parentID = '2'
$sth->execute(array($parentID));

// fetch the result here

$stmt->close();
cdaiga
  • 4,861
  • 3
  • 22
  • 42