How can PHP developers efficiently calculate and aggregate values from related rows in a database table?

To efficiently calculate and aggregate values from related rows in a database table, PHP developers can use SQL queries with aggregate functions like SUM, COUNT, AVG, etc. By grouping related rows using GROUP BY clause, developers can perform calculations on subsets of data. Then, PHP can be used to fetch and display the aggregated values to the end user.

<?php

// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Query to calculate and aggregate values
$sql = "SELECT category, SUM(quantity) as total_quantity FROM products GROUP BY category";

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

// Fetch and display the results
while ($row = $stmt->fetch()) {
    echo "Category: " . $row['category'] . ", Total Quantity: " . $row['total_quantity'] . "<br>";
}

?>