How can PHP code be structured to handle form submission and database insertion effectively?

To handle form submission and database insertion effectively in PHP, you can structure your code by first checking if the form has been submitted, then validating the form data, and finally inserting the data into the database. Make sure to use prepared statements to prevent SQL injection attacks.

<?php
// Check if the form has been submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    // Validate form data
    $name = $_POST['name'];
    $email = $_POST['email'];
    
    // Insert data into the database using prepared statements
    $stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
    $stmt->bindParam(':name', $name);
    $stmt->bindParam(':email', $email);
    $stmt->execute();
    
    // Redirect to a success page
    header("Location: success.php");
    exit();
}
?>