简体   繁体   中英

how to count all the children node of a parent node using php

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM