How can one use SQL functions like sum() and GROUP BY in PHP to calculate and display aggregated data from a database table?

To calculate and display aggregated data from a database table using SQL functions like sum() and GROUP BY in PHP, you can write a SQL query that includes these functions along with a GROUP BY clause to group the data accordingly. Then, execute the query using PHP's database connection and fetch the results to display the aggregated data.

<?php
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// SQL query to calculate and display aggregated data
$sql = "SELECT category, SUM(price) AS total_price FROM products GROUP BY category";

$result = $conn->query($sql);

// Display the aggregated data
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "Category: " . $row["category"]. " - Total Price: " . $row["total_price"]. "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();
?>