What are the best practices for filtering user input in PHP to prevent vulnerabilities like SQL injection?

To prevent vulnerabilities like SQL injection in PHP, it is essential to filter user input by using prepared statements or parameterized queries when interacting with a database. This approach separates the SQL query logic from the user input data, preventing malicious SQL code from being executed. Additionally, sanitizing and validating user input before processing it further can help mitigate potential security risks.

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

// Prepare a SQL statement with a placeholder for user input
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Bind the user input data to the placeholder
$stmt->bindParam(':username', $_POST['username']);

// Execute the prepared statement
$stmt->execute();

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