What are some best practices for structuring form data in PHP for insertion into a database?
When structuring form data in PHP for insertion into a database, it is best practice to sanitize and validate the input data to prevent SQL injection attacks and ensure data integrity. One common approach is to use prepared statements with parameterized queries to securely insert the form data into the database.
// Assuming $db 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);
// Prepare and execute a parameterized query
$stmt = $db->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
$stmt->execute();
// Check if the query was successful
if ($stmt->affected_rows > 0) {
echo "Data inserted successfully";
} else {
echo "Error inserting data";
}
// Close the statement and database connection
$stmt->close();
$db->close();