What are the best practices for handling user input validation and sanitization in PHP scripts to prevent SQL injection or other security risks?

To prevent SQL injection and other security risks in PHP scripts, it is essential to validate and sanitize user input. This can be done by using functions like htmlspecialchars() to prevent XSS attacks and prepared statements to prevent SQL injection.

// Validate and sanitize user input
$username = htmlspecialchars($_POST['username']);
$password = htmlspecialchars($_POST['password']);

// Create a prepared statement to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
$stmt->execute();