What are the potential pitfalls of not validating form data properly before inserting it into a database using PHP?

Not validating form data properly before inserting it into a database using PHP can lead to SQL injection attacks, data corruption, and security vulnerabilities. To mitigate these risks, always sanitize and validate user input before inserting it into the database.

// Validate and sanitize form data before inserting into the database
$name = isset($_POST['name']) ? htmlspecialchars($_POST['name']) : '';
$email = isset($_POST['email']) ? filter_var($_POST['email'], FILTER_SANITIZE_EMAIL) : '';
$age = isset($_POST['age']) ? filter_var($_POST['age'], FILTER_VALIDATE_INT) : 0;

// Insert validated data into the database
$stmt = $pdo->prepare("INSERT INTO users (name, email, age) VALUES (:name, :email, :age)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':age', $age);
$stmt->execute();