How can aggregate functions like SUM() be used in PHP to combine and display data?

Aggregate functions like SUM() can be used in PHP to combine and display data by querying a database and retrieving the aggregated result. This can be done by using SQL queries within PHP code to fetch the desired data and apply aggregate functions like SUM() to calculate the total. The result can then be displayed on a webpage or stored in a variable for further processing.

<?php
// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

// Query to calculate the sum of a column
$sql = "SELECT SUM(column_name) AS total FROM table_name";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "Total: " . $row["total"];
    }
} else {
    echo "0 results";
}

$conn->close();
?>