What best practices should be followed when handling user input and database operations in PHP scripts?

When handling user input in PHP scripts, it is important to validate and sanitize the input to prevent SQL injection attacks and other security vulnerabilities. Additionally, when performing database operations, it is recommended to use prepared statements to prevent SQL injection attacks and ensure data integrity.

// Example of validating and sanitizing user input
$username = $_POST['username'];
$password = $_POST['password'];

$username = filter_var($username, FILTER_SANITIZE_STRING);
$password = filter_var($password, FILTER_SANITIZE_STRING);

// Example of using prepared statements for database operations
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();