PHP Nested Loop Tutorial

A tutorial about nested loops in PHP and MySQL.

I guess since you are looking for a nested loop "solution" you already familiar with a simple database structure used in this method.

Open DW, create a table.

Create a recordset named "menu" to show only PARENT menu items which have SID value "0":

Insert dynamic text for MENU name field.

Create another Recordset and name it "submenu".
Note the SID equals $row_menu['id'], we will modify this later in the code view.

Create a second table under the first one, insert the Dynamic text from SUBMENU "menuname" Recordset and apply REPEAT REGION to both tables.

Now go to CODE VIEW and place the Recordset "submenu" under the closing </table> tag of the parent menu item table.
Look into the query where we typed earlier $row_menu['id'], we need slightly to change it.
Replace: $query_submenu = "SELECT * FROM menu WHERE sid = $row_menu['id']";
With: $query_submenu = "SELECT * FROM menu WHERE sid =".$row_menu['id']."";

This procedure could me much "cleaner" but i won't complicate things.
Dont forget to apply <?php tags ?> :)

Now we will loop the second table.
Type in repeat manualy, Dreamweaver will "complain" if you try to do it in design view.

<?php do { ?>
<?php while ($row_submenu = mysql_fetch_assoc($submenu)); ?>

Next we are going to....hey, thats it!!!





re this tutorial

September 29, 2005 by Alastair Sadler

Tried it and i've made some error!

What would be really useful is a link to the compleat page of code so I can compare and find my mistake.

Also a tripple nested tutorial  eg foods/nonfoods, fruits/veg. apples etc.

this tutorial has slight error

January 10, 2006 by Chris Pfrang
The statement: $query_submenu = "SELECT * FROM menu WHERE sid =".$row_menu['id'].""; should read: $query_submenu = "SELECT * FROM menu WHERE sid ='".$row_menu['id']."'"; Notice the extra ' before and after ".$row_menu['id']." If you are using a single table you may also want to add a GROUP BY sid to the first SQL statement before the ORDER BY statement

Has anyone been successful in making this tutorial work?

June 1, 2006 by John Robertson

As an absolute beginer I have also tried and not been able to make this tutorial work. The first comment raise doubts and I have tried to understand the alternatives.

If someone could revisit this tutorial and provide a known script that does work it would be appreciated.

Thanks in anticipation


no code only pictures?

May 17, 2008 by student 101

Pretty poor, due to no real code and only pictures, nobody can get this to work the way you have explained.

Post your entire page, love to see what that looks like?


See all 11 Comments

You must me logged in to write a comment.