What are some best practices for handling form submissions in PHP to avoid duplicate entries?

When handling form submissions in PHP, one common issue is the possibility of duplicate entries being inserted into a database if the form is submitted multiple times. To avoid this, you can implement a check to see if the data being submitted already exists in the database before inserting it. This can be done by checking for the existence of a unique identifier, such as an email address or username, in the database before inserting the new data.

// Check if the form has been submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    // Check if the email address already exists in the database
    $email = $_POST['email'];
    $query = "SELECT * FROM users WHERE email = '$email'";
    $result = mysqli_query($conn, $query);
    
    if (mysqli_num_rows($result) > 0) {
        // Email already exists, show an error message
        echo "Email already exists in the database";
    } else {
        // Insert the form data into the database
        $name = $_POST['name'];
        $email = $_POST['email'];
        $password = $_POST['password'];
        
        $insert_query = "INSERT INTO users (name, email, password) VALUES ('$name', '$email', '$password')";
        mysqli_query($conn, $insert_query);
        
        echo "Form submitted successfully";
    }
}