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

SQL injection vulnerabilities can occur when user input is not properly sanitized before being used in SQL queries, allowing malicious users to manipulate the query. To prevent this, it is important to use prepared statements with parameterized queries in PHP. This allows the database engine to distinguish between the SQL code and the user input, effectively preventing SQL injection attacks.

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

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

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

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

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