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 关注
- 106 浏览
添加回答
举报