PHP MySql loop through all child ID's
<p>I have MySql database which contains information about saved file and folder structures.</p>

<p>There is table called "Folder" which contains its "ID", "Name" and "ParentID".</p>

<p>Basically what I need to do is loop through all child folders and child folder's child folder and gather their ID's until there is no more child folders left.</p>

<p>Currently i have PHP script which contains function called <code>GetChilds($parentId)</code>.
Function runs SQL-query which gathers all Folder ID's where ParentID is <code>$parentID</code>. After that there is <code>foreach</code> loop calling same function again with found ID's.</p>

<p>This works as expected but its extremely slow and what I have read, it is not recommended to put queries inside loops in PHP.</p>

<p>So what I am looking for is alternative way to perform same functionality in more efficient way using either SQL-script or PHP.</p>

<p>EDIT:</p>

<p>Here is my code:</p>

<pre><code>private function FetchData($query, $query_params, $dbConnection)
{
    try
    {
        $stmt = $dbConnection-&gt;prepare($query); 

        if(count($query_params) &gt; 0)
            $stmt-&gt;execute($query_params); 
        else
            $stmt-&gt;execute();

            return $stmt-&gt;fetchAll();
    }
    catch(PDOException $e)
    {
        //Handle error
    }
}

private function GetChilds($parentId, $connection)
{
    $childFolders = $this-&gt;FetchData("select idFolder from Folder where ParentId = :parentId", array(":parentId" =&gt; $parentId), $connection);

    //Save ID's

    foreach($childFolders as $child)
    { 
        $this-&gt;GetChilds($child['idFolder'], $connection);
    }
}
</code></pre>