What are the best practices for handling form submissions in PHP to avoid duplicate database entries?
When handling form submissions in PHP, one common issue is the possibility of duplicate database entries if the form is submitted multiple times. To avoid this, you can implement a check before inserting data into the database to see if a similar entry already exists. This can be done by querying the database with the form data and checking if any matching records are found. If a match is found, you can choose to either update the existing record or display an error message to the user.
// Assuming $conn is the database connection object
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve form data
$name = $_POST['name'];
$email = $_POST['email'];
// Check if a similar entry already exists
$sql = "SELECT * FROM users WHERE name = '$name' AND email = '$email'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Display error message or update existing record
echo "Duplicate entry found!";
} else {
// Insert data into the database
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}