PHP实现同日期支付记录分组展示的技术求助
Hey there! To group your payment records by the date field and show all records from the same date in a single container, we need to adjust your code to track the current date and only create a new container when the date changes. Here's the modified code that achieves exactly what you're looking for:
<h1>Payment Record</h1> <?php $user_check = $_SESSION['login_user']; // Add ORDER BY date to ensure same-date records are grouped together in results $query = "SELECT * FROM `confirm_order` WHERE customer = '$user_check' ORDER BY date"; $result = mysqli_query($mysqli, $query); $current_date = null; $first_record = true; while ($row = mysqli_fetch_array($result)) { $row_date = $row['date']; // If we're moving to a new date, close the previous table (if it exists) if ($row_date !== $current_date) { if (!$first_record) { echo '</table>'; } // Start a new table for the new date echo '<table style="width:100%;border:1px solid black;margin-bottom:20px;">'; // Optional: Add a date header at the top of the grouped table echo '<tr><td colspan="2" style="font-weight:bold;">Date: ' . $row_date . '</td></tr>'; $current_date = $row_date; $first_record = false; } // Output the product details for this record echo '<tr>'; echo '<td>Product Name: ' . $row['product_name'] . '</td>'; echo '</tr>'; echo '<tr>'; echo '<td>Quantity: ' . $row['quantity'] . '</td>'; echo '</tr>'; echo '<tr>'; echo '<td>Receiver Name: ' . $row['receiver_name'] . '</td>'; echo '</tr>'; echo '<tr>'; echo '<td>Receiver Address: ' . $row['receiver_address'] . '</td>'; echo '</tr>'; echo '<tr>'; echo '<td>Receiver Contact: ' . $row['receiver_contact'] . '</td>'; echo '</tr>'; } // Close the last table after the loop ends if (!$first_record) { echo '</table>'; } ?>
Key Changes Explained:
- Sort Query by Date: Added
ORDER BY dateto the SQL query so all records with the same date are returned consecutively. This is critical for grouping them correctly. - Track Current Date: Used a variable
$current_dateto keep track of the date we're currently displaying. When the loop encounters a new date, it closes the previous table (if any) and starts a new one. - Handle Edge Cases: Added
$first_recordto avoid trying to close a table before the first one is created, and added code to close the final table after the loop finishes. - Optional Date Header: Added a bold date header at the top of each grouped table to make it clear which date the records belong to (feel free to remove this if you don't need it).
How It Works With Your Sample Data:
- For
date = 16/2, both the "book" and "pencil" records will live inside the same table container. - For
date = 18/2, the "shoe" record will be in its own separate table.
This matches the grouped display you're expecting!
内容的提问来源于stack exchange,提问作者Newbie
相关产品推荐
相关产品推荐

