in my code i need to use db_merge , that works well, but I'm looking for a way to show message when db_merge do not insert a record (to avoid duplication) the message would be : "you can't add this record because it exists in the db". The best way is try/catch, but it seems to work for db_selct,db_insert,db_update but not for db_merge.

  • I think the reason is because db_merge consists of a select + an update, I think there is no exception because the select is always working (in my opinion) – Mitch Aug 9 '15 at 11:43

A merge query does this:

  1. Does a record with the provided keys already exist in the database?
  2. If no, add it with the provided field values
  3. If yes, update the existing record with the provided field values.

Finding a duplicate isn't considered an exceptional circumstance, because that's what the query is designed to do; so no exception will be thrown.

If your aim is to support this statement:

"you can't add this record because it exists in the db"

Then a merge query might not be the right tool. db_insert() in a try...catch might make more sense in that case.

If you just want to know whether a record was added or updated, check the return value from MergeQuery::execute():

$result = $query->execute();
switch ($result) {
  case MergeQuery::STATUS_INSERT:
    // New record was added
  case MergeQuery::STATUS_UPDATE:
    // Existing record was updated
  • Like always Clive your answer is THE answer THANK YOU. the switch/case is the solution i was asking for thank you – Mitch Aug 9 '15 at 13:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.