Is there a generic way to INSERT IGNORE with PDO that will work on all database drivers?
If not, is it fair to assume the following would work:
try {
$stmt = $db->prepare("INSERT INTO link_table (id1, id2) VALUES (:id1, :id2)");
$stmt->execute(array( ':id1' => $id1, ':id2' => $id2 ));
}
catch (PDOException $ex) {
// Thanks to comment by Mike:
// Re-throw exception if it wasn't a constraint violation.
if ($ex->getCode() != 23000)
throw $ex;
}
AFAIK no there is not a generic version that will work with all database drivers.
INSERT IGNOREandINSERT...ON DUPLICATE KEY UPDATEare specific to MySQL.Checking for an existing record by selecting it first, or deleting an existing record and re-inserting are both prone to problems, including race conditions and possible foreign key constraint violations or cascading deletes.
I think your approach is probably the safest. You can always check the error code if you want to determine the cause of the exception – see:
http://docstore.mik.ua/orelly/java-ent/jenut/ch08_06.htm
I think you might want to check for code 23000.