Home > Net >  Merge rows of item column having the same date column and display items in single row in PHP
Merge rows of item column having the same date column and display items in single row in PHP

Time:11-18

I'm making an online shopping cart website and the customer must view all his/her orders in a table with all the order information like item names, price, date ordered, etc. And I want to group each order by date and display the items with same date in one row.

My table looks like this:

Orders Date Ordered
item1 11-23-2021
item2 11-23-2021
item3 12-30-2021

I want it to look like this:

Orders Date Ordered
item1, item2 11-23-2021
item3 12-30-2021

PHP:

<table>
  <tr>
    <th>Orders</th>
    <th>Date Ordered</th>
  </tr>

  <?php
   $showOrder = mysqli_query($conn, "SELECT * FROM orderdetails WHERE dateOrdered = '11-23-2021'
                            GROUP BY orderDate");

   while ($row = mysqli_fetch_array($showOrder)){
                    $item = $row['item'];
                    $date = $row['dateOrdered']; ?>
  <tr>
    <td><?php echo "<p>".$item."</p>"; ?></td>
    <td><?php echo "<p>".$date."</p>"; ?></td>
  </tr>
<?php } ?>
</table>

CodePudding user response:

You can use GROUP_CONCAT in MySQL query. For example,

SELECT GROUP_CONCAT(orders), date_ordered FROM orderdetails WHERE dateOrdered = '11-23-2021' GROUP BY orderDate

I presume your orderDate table has orders and date_ordered fields, You can modify according to your actual table column names.

You can read details like your own delimeters etc. here

  • Related