当两个查询相互依赖而第二个查询失败时,处理错误


Handling an error when two queries are dependent of eachother and the second one fails?

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

$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?
    }
}

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

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

//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');
}

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

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