【问题标题】:how to count all the children node of a parent node using php如何使用php计算父节点的所有子节点
【发布时间】:2018-07-23 15:32:33
【问题描述】:

这是我的桌子

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

这是我的php代码---->

 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;

}

现在我想使用上面的代码计算父节点的所有子节点,但我的代码给出了错误,例如 -->

致命错误:达到“100”的最大函数嵌套级别, 中止!在第 7 行的 C:\wamp\www\Project\index.php 中

【问题讨论】:

    标签: php mysql


    【解决方案1】:

    只需在查询中进行计数并将 parent_id 作为输入传递。使用prepared statements

    // ....
    
    $stmt = $db->prepare("SELECT COUNT(*) childrenCount FROM relation WHERE parentID=?");
    $parentID = '2'
    $sth->execute(array($parentID));
    
    // fetch the result here
    
    $stmt->close();
    

    【讨论】:

    • 感谢您的回复
    猜你喜欢
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    • 2015-06-25
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多