2
votes

I have a custom Drupal 7 module with an 'edit' page.

The form fields reference a couple of database tables, so to process the form, we attempt to update the first table, and we try to set a '$error' to 'true' and check against $error before we attempt to update the next table. For example:

HTML:

<input name="field1" />
<input name="field2" />

PHP:

$error = false;

$update_table_1 = db_update('table1')
    ->fields(array(
        'field1' => $_POST['field1'],
    ))
    ->condition('id', $id)
    ->execute();

if(!update_table_1) {
    $error = true;
}

if(!$error) {
    $update_table_2 = db_update('table2')
        ->fields(array(
            'field2' => $_POST['field2'],
        ))
        ->condition('id', $id)
        ->execute();

    if(!$update_table_2) {
        $error = true;
    }
}

Problem: If only updating something in table 2, it will throw an error before it event gets to update table 2 because db_query says that it is not true since the field was the same as what was in the database (no change). Really, I only want to stop it if there was a database / code error.

Does the Drupal 7 db_update API have some kind of error reporting function like mysql_error()? Other suggestions?

1
FYI, you might get more specific answers at drupal.stackexchange.com. - EmmyS

1 Answers

4
votes

The safest way you can do it is with a transaction and proper PHP error checking:

$transaction = db_transaction();

try {
  // Query 1
  db_update(...);

  // Query 2
  db_update(...);
}
catch (Exception $e) {
  // Rollback the transaction
  $transaction->rollback();

  // Do something with the exception (inform user, etc)
}

I should mention the transaction is only necessary if you don't want the changes from the first query to persist if the second query fails. It's quite a common requirement but might not fit your use case.