我對mysql事務有些懷疑。 我需要在兩個不同的表中同時創建兩個記錄,如果其中一個插入失敗,另一個不能保存。 這裏是我的代碼:Php mysql事務回滾疑惑
$conn->autocommit(FALSE);
$conn->query("START TRANSACTION");
// Insert values
$conn->query("INSERT INTO cards (id, points, reg_date, last_update) VALUES ('','$points', '$reg_date', '$reg_date')");
$card_id = $conn->insert_id;
$conn->query("INSERT INTO students (id, firstname, lastname, email, telephone, birthdate, address, city, cap, fiscal_code, username, card_id, password, token_password, reg_date, is_active)
VALUES ('','$student->firstname', '$student->lastname', '$student->email', '$student->telephone', '$student->birthdate', '$student->address', '$student->city', '$student->cap', '$student->fiscal_code', '$student->username', '$card_id','$student->password', '$student->token_password', '$student->reg_date', '$student->is_active')");
// Commit transaction
if (!$conn->commit()) {
print("Transaction commit failed\n");
$conn->rollback();
}
$conn->close();
$康恩鏈接包含的文件中創建的,我需要的是$因爲card_id的是在第二個查詢的值的外鍵。 問題是:如果第一個查詢失敗,一切正常,所以沒有記錄插入我的數據庫。但是,如果第二個查詢失敗,回滾將不起作用,第一個查詢中的記錄將保存在數據庫中。 編輯:我正在使用InnoDB。 我在哪裏做錯了?謝謝。
您正在使用哪種數據庫引擎? – sandeepsure
我忘了寫它,但我使用InnoDB。 – Ali