Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Group SQL results by date

I’m having trouble splitting the results from a SQL query into dates.
I have something like that:
i have something like that

And I want something like that:
i want this

// I use bootstrap...
$result = $conn->query($sql);
if ($result->num_rows > 0) {
  echo '<div class="list-group">';
  while($row = $result->fetch_assoc()) {

  $newDate = date("d.m.Y", strtotime($row["dataczas"]));
  $transactiontitle = $row["tytul"];

  echo '<a href="transakcja/?id='.$row["idTransakcji"].'" class="list-group-item list-group-item-action"> <div class="d-flex w-100 justify-content-between"> <h5 class="mb-1 text-truncate">'.$row["nazwa"].'</h5><small class="text-muted text-nowrap"><i class="bi bi-calendar3 text-muted"></i>&nbsp'.$newDate.'</small>
  </div>
  <p class="mb-1">'.$row["kwota"].' CAD</p>
  <p class="mb-1 text-truncate text-muted">
  '.
$transactiontitle
  .'
  </p>
  </a>';
  }



  echo "</div>";
} 

Above – my PHP code right now.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I would like to group rows by date like on the image above.

>Solution :

As far as I can see from your images, the output of the query is already sorted by date. So let me assume that that is indeed the case. All you have to do is print the date when it changes. You can do something like this:

$currentDate = '';
while($row = $result->fetch_assoc()) {
    $newDate = date("d.m.Y", strtotime($row["dataczas"]));
    if ($newDate != $currentDate) {
        echo 'Make date row here with date: ' . $newDate;
        $currentDate = $newDate;
    }
    // here comes the rest of the transaction
}

This code keep track of the current date, and whenever it changes it create a new date row in the output.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading