How can unique IDs and database constraints be utilized to prevent duplicate entries when handling form submissions in PHP?

To prevent duplicate entries when handling form submissions in PHP, unique IDs can be generated for each form submission and database constraints can be set to ensure that these IDs are unique. This way, if a user tries to submit the same form data again, the database will reject the duplicate entry based on the unique ID constraint.

// Generate a unique ID for the form submission
$unique_id = uniqid();

// Check if the unique ID already exists in the database
$query = "SELECT * FROM submissions WHERE unique_id = '$unique_id'";
$result = mysqli_query($connection, $query);

if(mysqli_num_rows($result) == 0) {
    // Insert the form data into the database
    $query = "INSERT INTO submissions (unique_id, form_data) VALUES ('$unique_id', '$form_data')";
    mysqli_query($connection, $query);
    echo "Form submitted successfully!";
} else {
    echo "Duplicate form submission detected!";
}