What are best practices for handling duplicate entries in PHP database queries?

When handling duplicate entries in PHP database queries, it is best practice to first check if the entry already exists before attempting to insert it. This can be done by querying the database to see if a record with the same data already exists. If a duplicate entry is found, you can either update the existing record or skip inserting the duplicate data altogether.

// Check if the entry already exists in the database
$query = "SELECT * FROM table_name WHERE column_name = :value";
$stmt = $pdo->prepare($query);
$stmt->bindParam(':value', $value);
$stmt->execute();
$existingEntry = $stmt->fetch();

if (!$existingEntry) {
    // Insert the new entry into the database
    $insertQuery = "INSERT INTO table_name (column_name) VALUES (:value)";
    $insertStmt = $pdo->prepare($insertQuery);
    $insertStmt->bindParam(':value', $value);
    $insertStmt->execute();
} else {
    // Update the existing entry or handle the duplicate entry in another way
    // For example: $updateQuery = "UPDATE table_name SET column_name = :new_value WHERE id = :id";
}