db_delete

Handling Drupal SQL exceptions (db_insert, db_update, db_delete)

While developing a Drupal module, I just ran into a situation where it may be common for users to generate SQL exceptions. I have a 'unique' limit on several of my database tables, essentially saying that certain name fields must be unique for the current project. As you can imagine, it's extremely easy to enter a duplicate name, and while doing a SQL INSERT that can easily lead to a SQL exception.

As a result, I dug around and found a way to handle SQL exceptions in Drupal queries. My current problem is with a Drupal 7 db_insert query, and I handled it like this:

A Drupal 7 SQL DELETE example

Drupal 7 SQL FAQ: How do I perform a SQL DELETE query in Drupal 7?

The short answer is that you use the Drupal 7 db_delete function, like this:

db_delete('projects')
  ->condition('id', 10)
  ->condition('user_id', 5)
  ->execute();

This example assumes that your database fields are named 'id' and 'user_id', and the values of 10 and 5 are the values in your database table you want to delete. If you just want to delete by id, your query is simpler, like this: