In PHP, what are the recommended methods for handling user input to prevent security vulnerabilities like SQL injection?

To prevent security vulnerabilities like SQL injection in PHP, it is recommended to use prepared statements with parameterized queries when interacting with a database. This helps to separate SQL logic from user input, preventing malicious SQL code from being executed.

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

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

// Bind parameters to the placeholders
$stmt->bindParam(':username', $_POST['username']);

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

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