How to read next row in a mySql Query

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Reboot
    New Member
    • Jan 2012
    • 2

    How to read next row in a mySql Query

    Hi!

    I have this php code which looks like this:
    Code:
    $sql = ......
    $result = mysql_query($sql,$connection)
    or die("Couldn't execute SELECT query");
     
    while ($row = mysql_fetch_array($result)) {
    ......
    }
    What i want to do is be able to read the next row in the query. So for example:
    Code:
    while ($row = mysql_fetch_array($result)) {
    ......
    if (ID for next row/record = ID for this row/record) {
    do this
    }
    }
    I almost got the solution , but the very last record for my query is always missing using this code:
    Code:
    $current_row=mysql_fetch_array($result); //read $current_row
    while ($next_row = mysql_fetch_array($result)) { //read $next_row
    ......
    if ($current_row['id']==$next_row['id']) { //compare it
    .....
    .....
    }
    $current_row=$next_row; //$next_row become current_row on next step
    }
    Thanks for any help
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    And it should be missing. The last row has no next row to compare to.

    Comment

    • Reboot
      New Member
      • Jan 2012
      • 2

      #3
      The user mikosiko (http://forums.devnetwork.net) gives me the perfect solution for this problem:
      Code:
      <?php
      
        // Example
        $heading_column = '<whatever is the name of your heading column>';
        $last_heading = null;
       
        while($row = your_fetch_assoc_statement){
              // detect a change in the heading value and output the new heading
              if($last_heading != $row[$heading_column]){
                      // detect if it is not the first heading - close out the previous section
                      if($last_heading != null){
                              // your code to close the previous section (table, div, etc)...
                              echo "close section<br />";
                      }
                      // output the new heading here...
                      echo "new section title - {$row[$heading_column]}<br />";
       
                      // save the new heading as the last_heading
                      $last_heading = $row[$heading_column];
              }
              // output the actual data here...
              echo "data - {$row['your_data']}<br />";
        }
        // if there was any output - close out the last section
        if($last_heading != null){
              // your code to close the previous section (table, div, etc)...
              echo "close section<br ?>";
        }
      ?>

      Comment

      Working...