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

SQL injection is a common security vulnerability where an attacker can manipulate user input to execute malicious SQL queries on a database. To prevent SQL injection in PHP, it is crucial to sanitize and validate user input before using it in SQL queries. One way to do this is by using prepared statements with parameterized queries, which separate SQL code from user input, making it impossible for attackers to inject malicious code.

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

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

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

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

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

// Use the results as needed
foreach ($results as $row) {
    echo $row['username'] . '<br>';
}