How can the SUM() and GROUP BY functions be used effectively in PHP to retrieve and calculate financial data?

To retrieve and calculate financial data using SUM() and GROUP BY functions in PHP, you can first fetch the data from your database using SQL queries that include the SUM() function to calculate totals. Then, use the GROUP BY clause to group the data based on a specific column, such as dates or categories. Finally, display or process the calculated results as needed.

// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "financial_data";

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

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

// SQL query to retrieve and calculate financial data
$sql = "SELECT category, SUM(amount) AS total_amount FROM transactions GROUP BY category";

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

if ($result->num_rows > 0) {
    // Output data of each row
    while($row = $result->fetch_assoc()) {
        echo "Category: " . $row["category"]. " - Total Amount: $" . $row["total_amount"]. "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();