How can you efficiently sort and display data from a database in PHP, specifically when summing and grouping values?
When sorting and displaying data from a database in PHP, especially when summing and grouping values, you can use SQL queries to retrieve the data in the desired format. You can use functions like SUM() and GROUP BY in your SQL query to calculate totals and group data accordingly. Once you have fetched the data from the database, you can iterate through the results and display them as needed.
<?php
// Connect to the database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Query to sum and group values
$query = "SELECT category, SUM(amount) AS total_amount FROM expenses GROUP BY category ORDER BY total_amount DESC";
$result = mysqli_query($connection, $query);
// Display the results
echo "<table>";
echo "<tr><th>Category</th><th>Total Amount</th></tr>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>".$row['category']."</td><td>".$row['total_amount']."</td></tr>";
}
echo "</table>";
// Close the connection
mysqli_close($connection);
?>