【发布时间】: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?
}
}
显然我会记录错误,但所有数据都会不同步/损坏。在这种情况下我该怎么办?还是我做错了整个事情,不应该出现在两个查询中?
【问题讨论】:
-
你需要使用
transactions,如果一切顺利,commit否则rollback -
参见 dev.mysql.com/doc/refman/5.7/en/commit.html ,取决于您用于连接 php 脚本和 mysql 服务器的 api,可能有“专门的”函数/方法,例如docs.php.net/manual/en/mysqli.begin-transaction.php
-
TRANSACTIONS (dev.mysql.com/doc/refman/5.7/en/commit.html) 是你的朋友...
标签: php mysql sql error-handling