1 回答

TA貢獻1777條經驗 獲得超3個贊
在這種情況下,您需要使用事務和回滾:
# start mysql transaction
mysqli_begin_transaction($conn, MYSQLI_TRANS_START_READ_WRITE);
$main_query = "INSERT INTO table_1 (...) VALUES (...)";
$res = mysqli_query($conn, $main_query);
if ($res)
{
? ? $id = mysqli_insert_id($conn);
? ??
? ? $sub_query = "INSERT INTO table_2 (...) VALUES (...)"; // use var "id" here
? ? $res = mysqli_query($conn, $sub_query);
? ? if ($res) {
? ? ? ? # both inserts succeed - do commit
? ? ? ? mysqli_commit($conn);
? ? }
? ? else {
? ? ? ? # second insert fail - do rollback
? ? ? ? mysqli_rollback($conn);?
? ? }
} else? {
? ? # first insert fail - do rollback
? ? mysqli_rollback($conn);?
}
或者我們可以使用面向對象的風格,例如:
# start mysql transaction
$mysqli->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
$main_query = "INSERT INTO table_1 (...) VALUES (...)";
$res = $mysqli->query($main_query);
if ($res)
{
? ? $id = $mysqli->insert_id;
? ? $sub_query = "INSERT INTO table_2 (...) VALUES (...)"; // use var "id" here
? ? $res = $mysqli->query($sub_query);
? ? if ($res) {
? ? ? ? # both inserts succeed - do commit
? ? ? ? $mysqli->commit();
? ? }
? ? else {
? ? ? ? # second insert fail - do rollback
? ? ? ? $mysqli->rollback();?
? ? }
} else? {
? ? # first insert fail - do rollback
? ? $mysqli->rollback();?
}
在這里查看工作示例PHPize.online
- 1 回答
- 0 關注
- 135 瀏覽
添加回答
舉報