Drupal 7 db_insert() execute() error when table contains unique keys I have a database (mysql) table that contains a unique key in barcode column.

What I intend is this:


I have a form that has a barcode field.
When user submits the form and the barcode entered already exists in the database table, I should just give an error message.
Currently, it gives me PDOException: ... Duplicate entry and the page contents does not load.


This is how I did the insert:

$insert = db_insert('mymodule_mytable')-&gt;fields($fieldarray)-&gt;execute();

At that line, Drupal 7 returns PDO error so I cannot execute the lines after it. Thus, I cannot also check the return value in $insert.

Is there workaround to avoid the PDO error? I need to do something like:

if($insert === FALSE) {
  drupal_set_message(t('Error'), 'error');
}
PHP has exception handling in the form of try...catch blocks:

try {
  $insert = db_insert('mymodule_mytable')-&gt;fields($fieldarray)-&gt;execute();
}
catch (PDOException $e) {
  drupal_set_message(t('Error: %message', array('%message' =&gt; $e-&gt;getMessage())), 'error');
}


So rather than ignore the error completely, you can actually respond to different types of exception and react accordingly.