How can SQL calculations be performed directly in the database to simplify data manipulation in PHP?

Performing SQL calculations directly in the database can simplify data manipulation in PHP by reducing the amount of data transferred between the database and the PHP application. This can improve performance and efficiency when working with large datasets. One way to achieve this is by using SQL functions and expressions to perform calculations within SQL queries, rather than retrieving raw data and processing it in PHP.

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

// Query to calculate the average price of products
$sql = "SELECT AVG(price) AS avg_price FROM products";

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

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

// Output the average price
echo "Average Price: " . $result['avg_price'];
?>