What best practices should be followed in PHP to ensure secure and efficient handling of form data before database insertion?
When handling form data in PHP before inserting it into a database, it is important to sanitize and validate the input to prevent SQL injection attacks and ensure data integrity. One common approach is to use prepared statements with parameterized queries to securely insert data into the database.
// Assuming $conn is your database connection
// Sanitize and validate form data
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
// Prepare SQL statement with placeholders
$stmt = $conn->prepare("INSERT INTO form_data (name, email, message) VALUES (?, ?, ?)");
// Bind parameters and execute query
$stmt->bind_param("sss", $name, $email, $message);
$stmt->execute();
// Close statement and connection
$stmt->close();
$conn->close();