How can SQL injection vulnerabilities be prevented when using user input in PHP queries for date filtering?

To prevent SQL injection vulnerabilities when using user input in PHP queries for date filtering, it is important to sanitize and validate the input before using it in the SQL query. One way to achieve this is by using prepared statements with parameterized queries, which separate the SQL query logic from the user input data. This helps to prevent malicious SQL code from being injected into the query.

// Assuming $startDate and $endDate are user input dates

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

// Prepare a SQL query using prepared statements
$stmt = $pdo->prepare("SELECT * FROM mytable WHERE date BETWEEN :start_date AND :end_date");

// Bind the sanitized user input to the prepared statement
$stmt->bindParam(':start_date', $startDate);
$stmt->bindParam(':end_date', $endDate);

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

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

// Use the results as needed
foreach ($results as $row) {
    // Process each row
}