What are some best practices for preventing duplicate entries in a database when using PHP forms?

To prevent duplicate entries in a database when using PHP forms, one best practice is to check if the data being submitted already exists in the database before inserting it. This can be done by querying the database with the submitted data and checking if any matching records are found. If a match is found, the form submission can be rejected to avoid duplicate entries.

// Assume $connection is the database connection object

// Check if the submitted data already exists in the database
$query = "SELECT * FROM table_name WHERE column_name = :submitted_data";
$stmt = $connection->prepare($query);
$stmt->bindParam(':submitted_data', $_POST['form_field']);
$stmt->execute();

if ($stmt->rowCount() > 0) {
    // Data already exists, reject form submission
    echo "Duplicate entry found";
} else {
    // Insert the data into the database
    $insert_query = "INSERT INTO table_name (column_name) VALUES (:submitted_data)";
    $insert_stmt = $connection->prepare($insert_query);
    $insert_stmt->bindParam(':submitted_data', $_POST['form_field']);
    $insert_stmt->execute();
    echo "Data inserted successfully";
}