Group SQL results by date

Advertisements

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.

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.

Leave a ReplyCancel reply