What are the best practices for handling user input and data manipulation in PHP to prevent syntax errors and ensure code efficiency?

When handling user input and data manipulation in PHP, it is important to sanitize and validate the input to prevent syntax errors and ensure code efficiency. One way to achieve this is by using functions like filter_var() to sanitize input and validate it against specific criteria. Additionally, using prepared statements when interacting with databases can help prevent SQL injection attacks.

// Example of sanitizing user input using filter_var()
$user_input = $_POST['user_input'];
$sanitized_input = filter_var($user_input, FILTER_SANITIZE_STRING);

// Example of validating email input
$email = $_POST['email'];
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
    // Valid email address
} else {
    // Invalid email address
}

// Example of using prepared statements to prevent SQL injection
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $username);
$stmt->execute();