Search code examples
phpmysqlnested-loops

mysqli_fetch_assoc loop inside of another mysqli_fetch_assoc loop


I've been searching the internet for a while trying to find this answer, but perhaps my search topics are just not right. I have an SQL query that returns the data from two tables into a combined results set. I want to loop through and find each "section" and print it out, and underneath each "section" I want to print out the events associated with that section. I basically have a parent loop to look for the "sections" and a child loop inside of the parent loop to search for events. My code is below.

Can anyone explain why the parent loop only iterates 1 time and then stops? I'd sure appreciate it!

while ($row = mysqli_fetch_assoc($result)) {
  if($row['ID'] != "") {
      echo '<h3 class="classTlt">'.$row['sTitle'].'</h3>';
      echo $row['sDesc']; 
      $table = '<table cellpadding="0" cellspacing="0" width="100%" border="0">
                  <tr>';
      for($i=1;$i<=6;$i++) {
         if($row['sH'.$i] != null) {
           $table .= '<th>'.$row['sH'.$i].'</th>';
         }
      }
      $table .= '</tr>';
      while ($row2 = mysqli_fetch_assoc($result)) {
        if($row2['sID'] == $row['ID']) {
          $table .= '<tr>';
          for($x=1;$x<=6;$x++) {
             if($row2['sV'.$x] != null) {
                 $table .= '<td valign="top">'.$row2['sV'.$x].'</td>';
             }//end if
          }//end for
          $table .= '</tr>';
        }//end if
      }//end while
      $table .= '</table>';
      echo $table; 
  }//end if
}//end while

Solution

  • You drain the result set dry within the inner loop.

    If your result has 10 rows, the outer while extracts 1, the inner extracts the other 9 and the outer has nothing to extract any more.

    Edit: in respect of the comments:

    $someArray = array();
    while ($row = mysqli_fetch_assoc($result)) {
      $someArray[] = $row;
    }
    
    for ($i = 0; $i < count($someArray); ++$i) {
      // some stuff
    
      for($j = 0; $j < count($someArray); ++$j) {
        // some more stuff
      }
    }