title: php loop through MySQL records - make decision based on row value
body: <p>I am using this code to loop through MySQL rows:</p>
  
  <pre><code>$sql = "SELECT * FROM vwPublicServices2 ORDER BY Service_Date__c, 
  Service_Time__c";
  $result = $conn-&gt;query($sql);
  
  if ($result-&gt;num_rows &gt; 0) {
      echo "&lt;table&gt;&lt;tr&gt;&lt;th&gt;Service Date&lt;/th&gt;&lt;th&gt;Service Time&lt;/th&gt;
      &lt;th&gt;Church&lt;/th&gt;&lt;th&gt;Service&lt;/th&gt;&lt;th&gt;Service Leader&lt;/th&gt;&lt;/tr&gt;";
  
      while($row = $result-&gt;fetch_assoc()) {    
  
         // insert header stuff on change of $date1
         if ($row["ServiceDate"] &lt;&gt; $date1) { 
  
            echo $row["ServiceDate"]. "(".$date1.")"."&lt;br/&gt;";
  
            echo "&lt;tr&gt;&lt;td&gt;" . $row["ServiceDate"]. "&lt;/td&gt;&lt;td&gt;" . 
            $row["Service_Time__c"]. "&lt;/td&gt;&lt;td&gt;" . $row["Location__c"]. "&lt;/td&gt;
            &lt;td&gt;" . $row["PublicName"]. "&lt;/td&gt;&lt;td&gt;" . $row["FullName"]."&lt;/td&gt;
            &lt;/tr&gt;";
  
            // set $date1 = row ServiceDate
            $date1 = $row["ServiceDate"];  
  
          } else {
  
            //  echo row data to follow on previous - i.e date has not 
            changed
            echo "&lt;tr&gt;&lt;td&gt;" . 
            $row["ServiceDate"]. "&lt;/td&gt;&lt;td&gt;" . 
            $row["Service_Time__c"]. "&lt;/td&gt;&lt;td&gt;" .
            $row["Location__c"]. "&lt;/td&gt;&lt;td&gt;" .
            $row["PublicName"]. "&lt;/td&gt;&lt;td&gt;" . 
            $row["FullName"]."&lt;/td&gt;&lt;/tr&gt;";
  
          }
  
       }
       echo "&lt;/table&gt;";
    } else {
       echo "0 results";
  }
  
  $conn-&gt;close();
  </code></pre>
  
  <p>Every time row["ServiceDate"] changes I want to insert some header data.
  Here are some of the results:</p>
  
  <p><a href="https://i.stack.imgur.com/kzj9V.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kzj9V.png" alt="Here are the first part of the results"></a></p>
  
  <p>There are two things I cannot understand - why is the date check 'one date out' i.e in the second line why is 14/05/2017 compared to 13/05/2017 ?<br>
  Also, why does the second echo statement not appear ?<br>
  I think I am missing some fundamental point with the way the while loop works !  Any help here much appreciated.  Thanks.</p>
  
  <p>Here is an illustration of the header insertion on date change using similar data to above. <em>(This web page pulls data from Salesforce  via their API and uses a similar date check to the one in the MySQL code above - but it loops through the data with a For..Each loop )</em>
  <a href="https://i.stack.imgur.com/kzm76.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kzm76.png" alt="enter image description here"></a></p>