What are the best practices for handling user input in PHP when switching from mysql_* to PDO?

When switching from mysql_* functions to PDO in PHP, it is important to handle user input securely to prevent SQL injection attacks. One best practice is to use prepared statements with bound parameters to sanitize and validate user input before executing queries.

// Connect to the database using PDO
$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 user input to the placeholder
$stmt->bindParam(':username', $_POST['username']);

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

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