How can a PHP developer ensure that user input, such as usernames and emails, is properly sanitized before being stored in a database?

To ensure that user input is properly sanitized before being stored in a database, a PHP developer can use prepared statements with parameterized queries to prevent SQL injection attacks. Additionally, they can use functions like htmlspecialchars() or filter_var() to sanitize user input for special characters or email validation.

// Example of sanitizing user input before storing in a database
$username = htmlspecialchars($_POST['username']);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

// Using prepared statements to prevent SQL injection
$stmt = $pdo->prepare("INSERT INTO users (username, email) VALUES (:username, :email)");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':email', $email);
$stmt->execute();