How can the SUM() function be utilized in PHP to calculate monthly totals for specific fields in a database query result?

To calculate monthly totals for specific fields in a database query result using the SUM() function in PHP, you can group the results by month and apply the SUM() function to the desired fields. This will allow you to retrieve the total sum of those fields for each month.

$query = "SELECT MONTH(date_field) as month, SUM(field_to_sum) as total_sum 
          FROM your_table 
          WHERE condition 
          GROUP BY MONTH(date_field)";

$result = mysqli_query($connection, $query);

while($row = mysqli_fetch_assoc($result)) {
    echo "Month: " . $row['month'] . " Total Sum: " . $row['total_sum'] . "<br>";
}