How can you prevent duplicate entries in a database when inserting form data in PHP?

To prevent duplicate entries in a database when inserting form data in PHP, you can first check if the data already exists in the database before inserting it. This can be done by querying the database with the form data to see if a matching entry already exists. If a matching entry is found, you can choose to either update the existing entry or display an error message to the user.

// Assuming $conn is the database connection object

// Check if the form data already exists in the database
$stmt = $conn->prepare("SELECT * FROM table_name WHERE column_name = ?");
$stmt->bind_param("s", $form_data);
$stmt->execute();
$result = $stmt->get_result();

if($result->num_rows > 0) {
    // Duplicate entry found, handle accordingly (e.g. display error message)
} else {
    // Insert the form data into the database
    $stmt = $conn->prepare("INSERT INTO table_name (column_name) VALUES (?)");
    $stmt->bind_param("s", $form_data);
    $stmt->execute();
}