What are some best practices for handling form submissions in PHP to ensure data integrity and user experience?

Issue: To ensure data integrity and a positive user experience when handling form submissions in PHP, it is important to validate the input data, sanitize it to prevent SQL injection attacks, and provide clear error messages to the user if any validation fails. PHP Code Snippet:

// Validate form data
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST["name"];
    $email = $_POST["email"];
    
    // Validate name
    if (empty($name)) {
        $errors[] = "Name is required";
    }
    
    // Validate email
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format";
    }
    
    // If no errors, proceed with form submission
    if (empty($errors)) {
        // Sanitize input data
        $name = htmlspecialchars($name);
        $email = filter_var($email, FILTER_SANITIZE_EMAIL);
        
        // Process form submission
        // Insert data into database, send email, etc.
    } else {
        // Display error messages to the user
        foreach ($errors as $error) {
            echo $error . "<br>";
        }
    }
}