Are there any best practices for aggregating values from a database in PHP?

When aggregating values from a database in PHP, it is best practice to use SQL functions such as SUM(), COUNT(), AVG(), etc. to perform calculations directly in the database query rather than fetching all the data and aggregating it in PHP code. This reduces the amount of data transferred between the database and PHP, improving performance and reducing the load on the server.

<?php
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Query to get the sum of a column named 'amount' from a table named 'transactions'
$sql = "SELECT SUM(amount) AS total_amount FROM transactions";

// Execute the query
$stmt = $pdo->query($sql);

// Fetch the result
$result = $stmt->fetch(PDO::FETCH_ASSOC);

// Output the total amount
echo "Total amount: " . $result['total_amount'];
?>