Are there any best practices for handling user input to prevent injection attacks?

To prevent injection attacks, it is essential to sanitize and validate user input before using it in database queries or other sensitive operations. One common best practice is to use prepared statements with parameterized queries, which help prevent SQL injection attacks by separating SQL code from user input.

// Using prepared statements to prevent SQL injection
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();
$user = $stmt->fetch();