What are some best practices for creating dynamic queries to calculate yearly sums in PHP?

When creating dynamic queries to calculate yearly sums in PHP, it is best practice to use prepared statements to prevent SQL injection attacks. Additionally, using functions like SUM() and GROUP BY in your SQL query can help calculate the yearly sums efficiently. Finally, consider using PHP date functions to dynamically generate the year in your query.

<?php
// Assuming $year is the dynamic year you want to calculate the sum for
$year = 2022;

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

// Prepare a SQL query to calculate the yearly sum
$stmt = $pdo->prepare("SELECT SUM(amount) as yearly_sum FROM your_table WHERE YEAR(date_column) = :year");
$stmt->bindParam(':year', $year, PDO::PARAM_INT);
$stmt->execute();

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

// Output the yearly sum
echo "Yearly sum for $year: " . $result['yearly_sum'];
?>