What are some best practices for dynamically building SQL queries in PHP to avoid repetitive code for different date ranges?

When dynamically building SQL queries in PHP to handle different date ranges, it's best to use prepared statements to prevent SQL injection vulnerabilities and to avoid repetitive code. By using placeholders for the date ranges, you can easily bind the values at runtime without having to rewrite the query for each date range.

// Sample code snippet for dynamically building SQL queries with date ranges using prepared statements

// Define the base query with placeholders for date ranges
$query = "SELECT * FROM table_name WHERE date_column BETWEEN :start_date AND :end_date";

// Prepare the SQL query
$stmt = $pdo->prepare($query);

// Bind the values for the date ranges
$start_date = '2022-01-01';
$end_date = '2022-12-31';
$stmt->bindParam(':start_date', $start_date, PDO::PARAM_STR);
$stmt->bindParam(':end_date', $end_date, PDO::PARAM_STR);

// Execute the query
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Loop through the results
foreach ($results as $result) {
    // Process each result
}