What are the best practices for handling user input validation in PHP to prevent SQL injection?

To prevent SQL injection in PHP, it is crucial to sanitize and validate user input before using it in database queries. One of the best practices is to use prepared statements with parameterized queries instead of directly inserting user input into SQL queries. This helps to separate the SQL logic from the user input, making it harder for attackers to inject malicious SQL code.

// Example of using prepared statements to prevent SQL injection
$pdo = new PDO("mysql:host=localhost;dbname=myDB", "username", "password");

// Sanitize and validate user input
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['password'], FILTER_SANITIZE_STRING);

// Prepare a SQL query using a prepared statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
$stmt->execute();

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