I have a table named as Organizations
id | organization | parent_id
-----+---------------+-----------
51 | Organ1 | 0
71 | Organ2 | 0
83 | Organ2.1 | 71
89 | Organ1.1 | 51
104 | Organ1.1.1 | 89
...
The organizations that have parent_id = 0
are the root organizations. Now I see I am wrong. parent_id
defines the organization's parent organization.
It looked a brilliant idea to me first. Thus, I would have created endless nested child organizations in a single table.
Now I am stuck how to determine how deep a organization is.
My current attempt is for now like the following:
<?php
$queryRootOrg = $db->prepare("SELECT * FROM Organizations WHERE parent_id = 0" );
$queryRootOrg ->execute();
$menu = "<ul id='menu'>";
if($queryRootOrg ->rowCount() > 0)
{
while($rowRoot = $queryRootOrg ->fetch(PDO::FETCH_ASSOC))
{
$menu .= "<li><a href='?org=".$rowRoot['id']."'>".$rowRoot['birim']."</a>";
$queryChildren= $db->prepare("SELECT * FROM Organizations WHERE parent_id = :p1");
$queryChildren->bindValue(":p1", $rowRoot['id'], PDO::PARAM_INT);
$queryChildren->execute();
if ($queryChildren->rowCount() > 0)
{
$menu .= "<ul>";
while($rowSub = $queryChildren->fetch(PDO::FETCH_ASSOC))
{
$menu .= "<li><a href='?org=" . $rowSub['id'] . "'>" . $rowSub['birim'] . "</a></li>";
}
$menu .= "</ul>";
}
$menu .= "</li>";
}
}
$menu .= "</ul>";
?>
This code brings me only two levels. I think I cannot see the third level organization in the list. My question is how come I know the depth of an organization in this circumstance? Or is there another approach?