0
$sth = $db->query("SELECT * FROM categories WHERE parent = 0");

$sth->setFetchMode(PDO::FETCH_ASSOC);

while ($row = $sth->fetch()) {

   echo $row['title'] . '<br />';

   $sth2 = $db->prepare("SELECT * FROM categories WHERE parent = ?");
   $sth2->bindParam(1, $row['id']);
   $sth2->execute();

   while ($row2 = $sth2->fetch()) {
        echo '..' . $row2['title'] . '<br />';

        $sth3 = $db->prepare("SELECT * FROM categories WHERE parent = ?");
        $sth3->bindParam(1, $row2['id']);
        $sth3->execute();

        while ($row3 = $sth3->fetch()) {
            echo '....' . $row3['title'] . '<br />';
        }
   }


}

As you can see I have 'hard coded' every while loop for mainly a "main category", 'a subcategory' and finally it's subcategory. However I feel that I could change this, to automatically, loop the subcategories in the subcategories, if there are such.

The structure is simple of my SQL: id parent title description

I am clueless how I should solve this little problem... A while loop over a if-statement or something? Help me out.

safarov
  • 7,793
  • 2
  • 36
  • 52
John
  • 2,900
  • 8
  • 36
  • 65

1 Answers1

0

What you can do if the number of categories is not too big, is get all categories in one go from the database and then build a multi-dimensional array in php.

See this question and the answers for more details.

Community
  • 1
  • 1
jeroen
  • 91,079
  • 21
  • 114
  • 132