【问题标题】:Handling an error when two queries are dependent of eachother and the second one fails?当两个查询相互依赖并且第二个查询失败时处理错误?
【发布时间】:2016-07-24 00:21:58
【问题描述】:

假设我需要插入一个表并更新另一个表,这两件事绝对需要一起发生。示例代码:

$insert = query('INSERT INTO first_table');

if ($insert->successful) {
    $update = query('UPDATE second_table');

    if ($update->successful) {

    } else {
        log($update->errorMessage);
        // magically revert the effects from the first query?
        // store the query and try to execute it on the next request?
    }
}

显然我会记录错误,但所有数据都会不同步/损坏。在这种情况下我该怎么办?还是我做错了整个事情,不应该出现在两个查询中?

【问题讨论】:

标签: php mysql sql error-handling


【解决方案1】:

您需要事务,另外验证启动事务的状态并提交

//Start your transaction
$start = query('START TRANSACTION');
$insert = query('INSERT INTO first_table');

if ($insert->successful) {
    $update = query('UPDATE second_table');

    if ($update->successful) {
        //Do the changes
        $state = query('COMMIT');
    } else {
        //Undo changes
        $state = query('ROLLBACK');
        log($update->errorMessage);
        // magically revert the effects from the first query?
        // store the query and try to execute it on the next request?
    }
} else {
    //Undo changes
    $state = query('ROLLBACK');
}

【讨论】:

    【解决方案2】:

    只有在两次查询都成功的情况下才需要启动事务并提交

    https://dev.mysql.com/doc/refman/5.5/en/commit.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-06
      • 1970-01-01
      • 2019-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多