亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

mysql - 如何檢查和回滾 mySql 查詢

mysql - 如何檢查和回滾 mySql 查詢

PHP
溫溫醬 2023-11-05 15:44:19
我有一個關于我使用 PHP 進行的 mySql 查詢的問題 -在我的代碼中,我將數據插入表 - main_query 。如果插入部分想要好,我會執行第二個插入查詢 - sub_query。如果第二個插入查詢失敗,如何取消第一個插入查詢?我的意思是 - 是否可以在實際執行之前發送兩個查詢以進行檢查?或者 - 是否可以回滾第一個“main_query”查詢?$main_query = "INSERT INTO table_1 (...) VALUES (...)";$res = $conn->query($main_query);if ($res){    $id = mysqli_insert_id($conn);        $sub_query = "INSERT INTO table_2 (...) VALUES (...)"; // use var "id" here    $res = $conn->query($sub_query);}
查看完整描述

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


查看完整回答
反對 回復 2023-11-05
  • 1 回答
  • 0 關注
  • 135 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號