What are the best practices for avoiding duplicate database entries when submitting form data multiple times?
To avoid duplicate database entries when submitting form data multiple times, you can implement a check in your PHP code to see if the data already exists in the database before inserting it. One way to do this is by checking for a unique identifier or key in the form data and querying the database to see if a record with that key already exists. If it does, you can update the existing record instead of inserting a new one.
// Check if the form has been submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Check if the data already exists in the database
$key = $_POST['unique_key']; // Change 'unique_key' to the actual unique identifier in your form data
$query = "SELECT * FROM your_table WHERE unique_key = '$key'";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
// Update existing record
$update_query = "UPDATE your_table SET column1 = 'new_value' WHERE unique_key = '$key'";
mysqli_query($connection, $update_query);
} else {
// Insert new record
$insert_query = "INSERT INTO your_table (unique_key, column1) VALUES ('$key', 'value')";
mysqli_query($connection, $insert_query);
}
}