title: Best way to identify a mysql changed "group by" field value in a statement fetch in php?
body: <p>I have a sql query in my php:</p>
  
  <pre><code>$sql = "SELECT * FROM orderTaken WHERE orderStatus='10' GROUP BY orderId ORDER BY orderTakenTime DESC";
  </code></pre>
  
  <p>Now, I have to echo back several HTML tables based on different orderIds, so basically if the orderId is changed, a new HTML table will be created and contains the info of all the things under this orderId. This is what I have done(kinda pseudocode, please ignore the syntax error. My real code is far more complicated but the idea is here: set an oldOrderId and check it with the newly fetched orderId and see if the orderId is changed):</p>
  
  <pre><code>$sql = "SELECT * FROM orderTaken WHERE orderStatus='10' GROUP BY orderId ORDER BY orderTakenTime DESC";
  $stmt = $pdo-&gt;prepare($sql);
  $stmt-&gt;execute();
  $count = $stmt-&gt;rowCount();
  for ($i = 0; $i&lt;$count + 1; $i++ ){
      if ($row = $stmt-&gt;fetch()){
          $orderId = $row["orderId"];
          $2ndField = $row["2ndField"];
          $3rdField = $row["3rdField"];
          ...
          // check if $oldOrderId is set
          if (isset($oldOrderId)){
              // and compare, if the orderId changes, end the table and create a new one
              if ($oldOrderId != $orderId){
                  echo "&lt;/table&gt;&lt;br&gt;";
                  echo "&lt;table&gt;&lt;tr&gt;&lt;th&gt;...&lt;/th&gt;&lt;/tr&gt;";
                  ...
                  //UPDATE old orderId
                  $oldOrderId = $orderId;
              // if orderId doesn't change, continue echo table content
              } else {
                  echo "&lt;table&gt;&lt;tr&gt;&lt;td&gt;...&lt;/td&gt;&lt;/tr&gt;";
              }
          // if the oldOrderId is not set, it means this is the first fetched row, and the very first table will be created
          } else {
              echo "&lt;table&gt;&lt;tr&gt;&lt;th&gt;...&lt;/th&gt;&lt;/tr&gt;";
              ...
              echo "&lt;table&gt;&lt;tr&gt;&lt;td&gt;...&lt;/td&gt;&lt;/tr&gt;";
              ...
              //SET oldOrderId
              $oldOrderId = $orderId;
          }
      }
      if ($i == $count) {
          //End the last table
          echo "&lt;/table&gt;&lt;br&gt;";
      }
  }
  </code></pre>
  
  <p>The code can run but will be buggy sometimes and I don't think this is a smart way to identify it. Is there any existed method like 
      $row = $stmt->fetch().prev()
  to get the last row's orderId's value? Or if there's any better way to perform it?</p>
  
  <p>Thanks!</p>