What are the best practices for handling calculations and data manipulation in PHP when working with database tables?

When working with database tables in PHP, it is best practice to offload calculations and data manipulation to the database itself whenever possible. This can be achieved by utilizing SQL queries to perform operations directly on the data stored in the tables, rather than fetching the data into PHP and manipulating it there. This approach can improve performance and reduce the amount of data transferred between the database and the PHP application.

// Example of performing calculations in SQL query
$query = "SELECT SUM(amount) AS total_amount FROM transactions WHERE status = 'completed'";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);
$totalAmount = $row['total_amount'];
echo "Total amount of completed transactions: $totalAmount";