How can SQL injection and XSS vulnerabilities be mitigated in this PHP code?

To mitigate SQL injection vulnerabilities, you should use prepared statements with parameterized queries instead of directly inserting user input into SQL queries. To prevent XSS vulnerabilities, you should sanitize user input before displaying it on the page by using functions like htmlspecialchars.

// Mitigating SQL injection vulnerability with prepared statements
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();

// Mitigating XSS vulnerability by sanitizing user input before displaying
echo htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');