What are some best practices for handling form data in PHP before inserting it into a database?

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 best practice is to use prepared statements with parameterized queries to securely insert data into the database.

// Assuming $conn is the database connection object

// Sanitize and validate form data
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);

// Prepare SQL statement with parameterized query
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);

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

// Close the statement and database connection
$stmt->close();
$conn->close();