How can SQL views be utilized to optimize data presentation and calculations in PHP applications?

SQL views can be utilized in PHP applications to optimize data presentation and calculations by abstracting complex queries into reusable virtual tables. By creating views that encapsulate frequently used joins, aggregations, or calculations, developers can simplify their PHP code and improve performance by offloading these operations to the database server. This can result in cleaner, more maintainable code and reduced processing time for data-intensive applications.

<?php

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

// Create a SQL view that calculates the total revenue for each product
$sql = "CREATE VIEW product_revenue AS
        SELECT product_id, SUM(quantity * price) AS total_revenue
        FROM sales
        GROUP BY product_id";

// Prepare and execute the SQL statement
$statement = $pdo->prepare($sql);
$statement->execute();

// Query the view to get the total revenue for a specific product
$product_id = 1;
$query = "SELECT total_revenue FROM product_revenue WHERE product_id = :product_id";
$statement = $pdo->prepare($query);
$statement->bindParam(':product_id', $product_id);
$statement->execute();
$result = $statement->fetch(PDO::FETCH_ASSOC);

echo "Total revenue for product $product_id: $" . $result['total_revenue'];

?>