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

If form data is not properly validated before inserting it into a database in PHP, it can lead to security vulnerabilities such as SQL injection attacks, where malicious code is inserted into the database. This can result in data loss, data corruption, or unauthorized access to sensitive information. To prevent this, always sanitize and validate user input before inserting it into the database.

// Example of validating and sanitizing form data before inserting it into a database
$name = $_POST['name'];
$email = $_POST['email'];

// Validate and sanitize input
$name = filter_var($name, FILTER_SANITIZE_STRING);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);

// Prepare SQL statement
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);

// Execute the statement
$stmt->execute();