Drupal 7 db_update -检查错误


Drupal 7 db_update - checking for errors

我有一个带有'edit'页面的自定义Drupal 7模块。

表单字段引用了几个数据库表,因此为了处理表单,我们尝试更新第一个表,并尝试将'$error'设置为'true',并在尝试更新下一个表之前检查$error。例如:

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;
    }
}

问题:如果只更新表2中的内容,它将在事件更新表2之前抛出错误,因为db_query说这不是真的,因为字段与数据库中的内容相同(没有更改)。真的,我只想在数据库/代码出现错误时停止它。

Drupal 7的db_update API有类似mysql_error()的错误报告功能吗?其他建议吗?

最安全的方法是使用事务和适当的PHP错误检查:

$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)
}
我应该提到,只有当您不希望在第二个查询失败时第一个查询的更改持久化时,才需要事务。这是一个非常常见的需求,但可能不适合您的用例。