2

In drupal 6 my code worked like this:

if (db_query("DELETE FROM {,ymodule_fields} WHERE conid = %d", $conid)) {
  drupal_set_message(t("Deleted fields."));
}

Now I'm supposed to use db_delete.

Will this code work? I know db_delete returns a DeleteQuery object so I'm assuming it's going to evaluate to true every time. I can't test my module yet because I'm doing a lot of work updating the code that creates cck fields to use core fields. Is DeleteQuery a PDO that has the rowCount method?

if (db_delete('mymodule_fields')
  ->condition('conid', $conid)
  ->execute()) {
  drupal_set_message(t("Deleted Fields."));
}

1 Answer 1

2

Sure, db_delete() returns an object so you can continue working with the object, but the last method called (the method whose return value your conditional is really checking) in your statement is Query::execute, which returns boolean TRUE or FALSE indicating whether the query worked. So, ultimately the whole statement:

db_delete('drealty_fields')
  ->condition('conid', $conid)
  ->execute();

Should return TRUE or FALSE since you're ultimately executing the Query::execute method. The workflow is just that you call db_delete(), which returns an object, Query::condition, returns an object, then Query::execute returns boolean, but your conditional is just getting and checking the return value of the last method called - execute - rather than the return value of db_delete(). Essentially, the db_delete() return value was already operated on by continuing with a condition, and the condition's return value is inconsequential because it was operated on by execute, thus the execute's return value is the only one really getting sent back to the if statement. Make sense?

So, in essence each of these examples should give the same results:

$query = db_delete('drealty_fields');
$query->condition('conid', $conid);
$success = $query->execute();
if ($success) {
  // Do something.
}

$query = db_delete('drealty_fields');
$query->condition('conid', $conid);
if ($query->execute()) {
  // Do something.
}

if (db_delete('drealty_field's)->condition('conid', $conid)->execute()) {
  // Do something.
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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