Can you provide an example of how to validate form entries before inserting them into a database in PHP?
When inserting form entries into a database in PHP, it is important to validate the data to ensure it meets the required criteria and prevent SQL injection attacks. One way to do this is by using PHP's filter_var function to sanitize and validate the input before inserting it into the database.
// Validate form entries before inserting into the database
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
// Check if the input is valid
if ($name && $email) {
// Insert the validated data into the database
$query = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
// Execute the query
$result = mysqli_query($connection, $query);
if ($result) {
echo "Data inserted successfully";
} else {
echo "Error inserting data into the database";
}
} else {
echo "Invalid input data";
}