How can user input be securely handled in PHP scripts to prevent SQL injection attacks?

To prevent SQL injection attacks in PHP scripts, user input should be sanitized and validated before being used in SQL queries. This can be achieved by using prepared statements with parameterized queries or by using functions like mysqli_real_escape_string() to escape special characters in the input.

// Example of using prepared statements to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$username]);
$results = $stmt->fetchAll();