Replies Back to Article

PHP Nested Loop Tutorial

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?

Cheers

RE: Has anyone been successful in making this tutorial work?
May 18, 2008 by student 101

<?php require_once('../../Connections/cnparent.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;   
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

mysql_select_db($database_cnparent, $cnparent);
$query_menu = "SELECT * FROM parent WHERE sid = 0 ORDER BY menuname ASC";
$menu = mysql_query($query_menu, $cnparent) or die(mysql_error());
$row_menu = mysql_fetch_assoc($menu);
$totalRows_menu = mysql_num_rows($menu);

//mysql_select_db($database_cnparent, $cnparent);
//$query_submenu = "SELECT * FROM menu WHERE sid =".$row_menu['id']."";
////$query_submenu = "SELECT * FROM parent WHERE sid = $row_menu['id']";
//$submenu = mysql_query($query_submenu, $cnparent) or die(mysql_error());
//$row_submenu = mysql_fetch_assoc($submenu);
//$totalRows_submenu = mysql_num_rows($submenu);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "
http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset="iso-8859-1"">
<title>PHP Nested Loop</title>
</head>
<body>
<p>PHP Nested Loop</p>
<?php do { ?>
<table width="300" border="0" cellspacing="0" cellpadding="0">
<tr>
<td><?php echo $row_menu['menuname']; ?></td>
</tr>
</table>
<?php
mysql_select_db($database_cnparent, $cnparent);
$query_submenu = "SELECT * FROM menu WHERE sid ='".$row_menu['id']."'";
//$query_submenu = "SELECT * FROM menu WHERE sid =".$row_menu['id']."";
$submenu = mysql_query($query_submenu, $cnparent) or die(mysql_error());
$row_submenu = mysql_fetch_assoc($submenu);
$totalRows_submenu = mysql_num_rows($submenu);
?>
<?php do { ?>
  <table width="300" border="0" cellspacing="0" cellpadding="0">
    <tr>
      <td><?php echo $row_submenu['menuname']; ?></td>
    </tr>
</table>
<?php } while ($row_submenu = mysql_fetch_assoc($submenu)); ?>
<?php } while ($row_menu = mysql_fetch_assoc($menu)); ?>
</body>
</html>
<?php
mysql_free_result($menu);

mysql_free_result($submenu);
?>

There is my code, it wont ever work.

Cheers

 

RE: no code only pictures?
May 18, 2008 by John Robertson
Greetings Jason
 
Thank you for your persistance in wanting to find an answer to this article. For a long time (would you believe - now nearly TWO YEARS since I first asked the same question) I did not believe anyone could solve this (or want to - to assist us all).
 
Well I have some great news - I have it working.
 
I wish I had this answer back then!
 
Firstly I created my database - Using "NAVICAT". I highly commend this package. http://www.navicat.com/download.html
 
Here is my SQL list
 
/*
MySQL Data Transfer
Source Host: localhost
Source Database: demo
Target Host: localhost
Target Database: demo
Date: 19/05/2008 11:42:18 AM
*/
SET foreign_key_checks="0;"
-- ----------------------------
-- Table structure for menu
-- ----------------------------
CREATE TABLE `menu` (
  `id` int(11) NOT NULL auto_increment,
  `sid` varchar(255) default NULL,
  `menuname` varchar(255) default NULL,
  PRIMARY KEY  (`id`)
) engine="InnoDB" DEFAULT charset="latin1;"
-- ----------------------------
-- Records
-- ----------------------------
INSERT INTO `menu` VALUES ('1', '0', 'Fruits');
INSERT INTO `menu` VALUES ('2', '1', 'Apples');
INSERT INTO `menu` VALUES ('3', '1', 'Orange');
INSERT INTO `menu` VALUES ('4', '1', 'Apricots');
INSERT INTO `menu` VALUES ('5', '1', 'Lemon');
INSERT INTO `menu` VALUES ('6', '0', 'Vegetables');
INSERT INTO `menu` VALUES ('7', '6', 'Tomatoes');
INSERT INTO `menu` VALUES ('8', '6', 'Potatoes');
INSERT INTO `menu` VALUES ('9', '6', 'Cucumbers');
INSERT INTO `menu` VALUES ('10', '6', 'Asparagus');
INSERT INTO `menu` VALUES ('11', '0', 'Sweets');
INSERT INTO `menu` VALUES ('12', '11', 'Scones');
INSERT INTO `menu` VALUES ('13', '11', 'Cakes');
INSERT INTO `menu` VALUES ('14', '11', 'Picklets');
INSERT INTO `menu` VALUES ('15', '0', 'Savouries');
INSERT INTO `menu` VALUES ('16', '15', 'Sandwiches');
INSERT INTO `menu` VALUES ('17', '15', 'Sausage Rolls');
-----------------------------------------------
 
I have added further items to demo features further.
 
Now for the code for the page
 
-----------------------------------------------
<?php require_once('../Connections/demo.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;   
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}
$maxRows_menu = 10;
$pageNum_menu = 0;
if (isset($_GET['pageNum_menu'])) {
  $pageNum_menu = $_GET['pageNum_menu'];
}
$startRow_menu = $pageNum_menu * $maxRows_menu;
mysql_select_db($database_demo, $demo);
$query_menu = "SELECT * FROM menu WHERE sid = '0' ORDER by menuname ASC";
$query_limit_menu = sprintf("%s LIMIT %d, %d", $query_menu, $startRow_menu, $maxRows_menu);
$menu = mysql_query($query_limit_menu, $demo) or die(mysql_error());
$row_menu = mysql_fetch_assoc($menu);
if (isset($_GET['totalRows_menu'])) {
  $totalRows_menu = $_GET['totalRows_menu'];
} else {
  $all_menu = mysql_query($query_menu);
  $totalRows_menu = mysql_num_rows($all_menu);
}
$totalPages_menu = ceil($totalRows_menu/$maxRows_menu)-1;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset="utf-8"" />
<title>Nested Loops</title>
</head>
<body style="font-family:Arial, Helvetica, sans-serif; font-size:12px;">
 <?php do { ?>
      <table width="500" border="0" cellspacing="0" cellpadding="0">
        <tr>
          <td style="color:#990000; font-weight:bold"><?php echo $row_menu['menuname']; ?></td>
        </tr>
        </table>
        <?php
                mysql_select_db($database_demo, $demo);
                $query_submenu = "SELECT * FROM menu WHERE sid = '".$row_menu['id']."' ORDER by menuname ASC";
                $submenu = mysql_query($query_submenu, $demo) or die(mysql_error());
                $row_submenu = mysql_fetch_assoc($submenu);
                $totalRows_submenu = mysql_num_rows($submenu);
            ?>
       <?php do { ?>
            <table width="500" border="0" cellspacing="0" cellpadding="0">
            <tr>
              <td>&nbsp;&nbsp;&nbsp;&nbsp;<?php echo $row_submenu['menuname']; ?></td>
            </tr>
            </table>
        <?php } while ($row_submenu = mysql_fetch_assoc($submenu)); ?>
   <?php } while ($row_menu = mysql_fetch_assoc($menu)); ?>
</body>
</html>
<?php
mysql_free_result($menu);
mysql_free_result($submenu);
?>
 
--------------------------------------------------

I believe the first line will be the only line you will need to change - to suit your database connection!
 
As you will see in the SELECT statements I have added the ORDER to ascending.
 
By changing the sid for each item determines its nest.
 
Please let us know if you also are successful.
 
Bless ya heaps
 
alias AceTutor
Review of Jayson's code
May 18, 2008 by John Robertson

Hi again Jayson.

I compared our code and see why yours was not working.

 

mysql_select_db($database_cnparent, $cnparent);
$query_menu = "SELECT * FROM parent WHERE sid = 0 ORDER BY menuname ASC";
$menu = mysql_query($query_menu, $cnparent) or die(mysql_error());
$row_menu = mysql_fetch_assoc($menu);
$totalRows_menu = mysql_num_rows($menu);

I changed parent to menuand it worked fine

 

Again thanks

AceTutor

PS Sorry that my posted code below looks yuk!

RE: Review of Jayson's code
May 19, 2008 by student 101

Thank you!

Cheers

RE: Review of Jayson's code
May 19, 2008 by student 101

Works similar to my asp version.
Thank you for taking the time.

Cheers

SOLVED - THIS SOLUTION WORKS
June 5, 2008 by A. Hos

Just read Chris Pfrang's post (10 January 2006, 10:51).  I followed the tutorial THEN implemented his two small fixes/adjustments. It worked like a charm!

 

Thank you Chris and Zo Zo.

Awesome.....
November 13, 2009 by Adrian Lord

I just wanted to say a big THANKS for this tutorial. I have been looking for ages for a simple step by step guide on how to next tables within tables. I followed your guide (although I have separate tables for the "menu" and "submenu" parts) and it worked perfectly. You are my hero, and I want to have your babies! :) - Ade