Why is it important to sanitize and validate user input when using PHP for database queries?

It is important to sanitize and validate user input when using PHP for database queries to prevent SQL injection attacks, where malicious code is inserted into input fields to manipulate the database. Sanitizing input involves removing any potentially harmful characters, while validation ensures that the input meets the expected format or criteria.

// Sanitize and validate user input
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);

// Prepare and execute the database query
$stmt = $pdo->prepare("INSERT INTO users (username, email) VALUES (:username, :email)");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':email', $email);
$stmt->execute();