How can you efficiently handle form validation and database insertion in PHP to ensure data integrity?

To efficiently handle form validation and database insertion in PHP to ensure data integrity, you can use server-side validation to check the input data before inserting it into the database. This involves validating each form field against predefined rules (such as required fields, data format, length limits, etc.) and sanitizing the input to prevent SQL injection attacks. Once the data passes validation, you can safely insert it into the database using prepared statements to prevent SQL injection.

<?php
// Validate form data
$errors = array();

if(empty($_POST['username'])) {
    $errors[] = "Username is required";
}

// Add more validation rules for other form fields

if(empty($errors)) {
    // Sanitize input data
    $username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
    
    // Establish database connection
    $conn = new mysqli('localhost', 'username', 'password', 'database');

    // Prepare and bind SQL statement
    $stmt = $conn->prepare("INSERT INTO users (username) VALUES (?)");
    $stmt->bind_param("s", $username);

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

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

    echo "Data inserted successfully";
} else {
    foreach($errors as $error) {
        echo $error . "<br>";
    }
}
?>