How can PHP be used to validate and process user input from a form before storing it in a database for further processing?

To validate and process user input from a form before storing it in a database, you can use PHP to sanitize and validate the data to prevent SQL injection and other security vulnerabilities. This can be achieved by using functions like htmlspecialchars() to prevent XSS attacks and prepared statements to prevent SQL injection. Additionally, you can implement server-side validation to ensure that the data meets the required format before storing it in the database.

<?php
// Assuming form data is submitted via POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = htmlspecialchars($_POST["name"]);
    $email = htmlspecialchars($_POST["email"]);
    
    // Validate email format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "Invalid email format";
    } else {
        // Connect to database and insert sanitized data using prepared statements
        $conn = new mysqli("localhost", "username", "password", "dbname");
        
        $stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
        $stmt->bind_param("ss", $name, $email);
        
        if ($stmt->execute()) {
            echo "Data stored successfully";
        } else {
            echo "Error storing data";
        }
        
        $stmt->close();
        $conn->close();
    }
}
?>