How can PHP developers ensure that data entered through a form is properly sanitized and formatted before being inserted into a database table?
To ensure that data entered through a form is properly sanitized and formatted before being inserted into a database table, PHP developers can use functions like filter_var() to sanitize input data and prepared statements to prevent SQL injection attacks. By combining these techniques, developers can protect their database from malicious input and ensure data integrity.
// Sanitize input data
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
// Prepare the SQL statement
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
// Bind parameters
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
// Execute the statement
$stmt->execute();