db_delete

7 database.inc db_delete($table, array $options = array())
8 database.inc db_delete($table, array $options = array())

Returns a new DeleteQuery object for the active database.

Parameters

$table: The table from which to delete.

$options: An array of options to control how the query operates.

Return value

DeleteQuery A new DeleteQuery object for this connection.

Related topics

166 functions call db_delete()

File

includes/database/database.inc, line 2448
Core systems for the database layer.

Code

<?php
function db_delete($table, array $options = array()) {
  if (empty($options['target']) || $options['target'] == 'slave') {
    $options['target'] = 'default';
  }
  return Database::getConnection($options['target'])->delete($table, $options);
}
?>

Comments

Example #1

Simple example taken from http://drupal.org/node/310081

<?php

// Drupal 7
$nid = 5;
$num_deleted = db_delete('node')
  ->
condition('nid', $nid)
  ->
execute();

// Above example is equivalent to the following in Drupal 6
$nid = 5;
db_query("DELETE FROM {node} WHERE nid = %d", $nid);

?>

Example #2

Another simple example, but with two conditional clauses, based on the Conditional clauses documentation at http://drupal.org/node/310086

<?php
$and
= db_and()->condition('mid', 1)->condition('cache_type', 'year');
db_delete('mid_cache_index')->condition($and)->execute();  

// Above translates to:
DELETE FROM {mid_cache_indexWHERE ( (mid = 1) AND (cache_type = 'year') )
?>

Improved Example #2

I believe It's better to write this way instead of adding db_and() in this case. Fix me if I'm wrong.

<?php
db_delete
('mid_cache_index')
  ->
condition('mid', 1)
  ->
condition('cache_type', 'year')
  ->
execute();
?>

Login or register to post comments