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:

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

Or, if you prefer seeing PHP variables, my current code looks like this:

db_delete('sleet_projects')
  ->condition('id', $project_id_to_delete)
  ->condition('user_id', get_user_id())
  ->execute();

For more information on this SQL DELETE function, see the Drupal 7 db_delete documentation page.

I'll be glad to share more code related to the SQL DELETE process in a Drupal form/module; if you're interested in seeing my Drupal form delete function and submit handler, just leave a note here and I'll be glad to share all of that.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.