What are the best practices for handling form data validation and error checking in PHP before inserting into a database?

When handling form data validation and error checking in PHP before inserting into a database, it is important to sanitize and validate the input to prevent SQL injection attacks and ensure data integrity. One common practice is to use PHP functions like filter_input() or prepared statements to sanitize and validate user input before inserting it into the database.

// Example of handling form data validation and error checking in PHP before inserting into a database

// Validate and sanitize form input
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);

// Check for errors
if (!$name || !$email) {
    echo "Invalid input. Please check your form data.";
    exit;
}

// Insert data into database using prepared statements
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);

if ($stmt->execute()) {
    echo "Data inserted successfully.";
} else {
    echo "Error inserting data into database.";
}