I want to count number of all child nodes under any level of tree structure maintained in a table using adjacency model (parent-child key). Table structure and data looks l
Below is a PHP based solution:
function countChildren($startId) {
$directDescendents = *_query("SELECT id FROM Table WHERE parentid = ?", array( $startId ));
$count = *_num_rows($directDescendents);
while($row = *_fetch_array($directDescendents))
$count += countChildren($row['id']);
return $count;
}
$numChildren = countChildren(2); // Number of Children for 'B'
Replace *_num_rows and *_fetch_array with whatever functions for the SQL extension you are using. This won't be as efficient as a pure SQL solution, but it will work. The way I'm querying in the function is assuming bound parameters, but execute the query as you like.