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

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

// 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();