起因
無意間翻看極客學院的APP,准備找一些教程看看.看到一篇PDO 安全處理與事務處理,一想對MySQL的事務處理僅僅停留在概念上(知道執行多條語句,其中一個失敗了,就會回滾操作)。但是把概念變成代碼還真沒實踐過,於是就打開了。
視頻講解的還是比較基礎詳細的:
MySQL數據表應該為InnoDB類型
事務處理操作方法主要包括:
-
beginTransaction() //開啟一個事務
-
commit() //事務提交
-
rollBack() //事務回滾操作
PS:
PDO::ATTR_ERRMODE:錯誤報告
PDO::ERRMODE_SILENT: 僅設置錯誤代碼
PDO::ERRMODE_WARNING: 引發 E_WARNING 錯誤
PDO::ERRMODE_EXCEPTION: 拋出 exceptions 異常
但是其中一段代碼是有問題的,首先我看到的是roolback拼錯了,然后仔細一看:先die掉,然后執行rollBack方法,肯定是有問題的啊。
但是實際執行過程中,因為對name字段有個唯一索引,事務並沒有成功提交。而且rollBack方法也沒有執行。但是數據卻沒有插入。本來想着一上午就搞定的問題,因為這個問題的出現,導致又花費幾個小時解決。
問題
問題:Is it necessary to rollback if commit fails?
$mysqli->autocommit(false); //Start the transaction
$success = true;
/* do a bunch of inserts here, which will be rolled back and
set $success to false if they fail */
if ($success) {
if ($mysqli->commit()) {
/* display success message, possibly redirect to another page */
}
else {
/* display error message */
$mysqli->rollback(); //<----------- Do I need this?
}
}
$mysqli->autocommit(true); //Turns autocommit back on (will be turned off again if needed)
//Keep running regardless, possibly executing more inserts
SF上也有相同的疑問~~~ 並且沒人能解答。
解決
緊接着又找,看來也有人跟我相同的疑問,rollBack方法會自動執行?終於找到了答案!
If you don't commit not rollback an opened transaction, and it's not commited anywhere later in your script, it won't be commited (as seen by the database engine), and will automatically rolled-back at the end of your script.
上述引用大概的意思是:在開啟一個事物沒有執行commit方法或者rollBack方法,在腳本最后也不會執行commit方法並且在腳本最后將會執行rollBack方法。
參考中還提到方便別人理解,否則別人不知道是否需要回滾操作,還是之后寫了。
The code is more easy to read / understand : when one sees $db->rollback(), he knows I want the transaction rolled-back for sure, and he doesn't have to think "did he really want to rollback, or did he forget something ? and what about later in the script ?"
注意
因此,設想唯一索引字段插入了一條相同的數據,導致程序進入捕捉了異常。此時沒有寫rollback執行回滾操作。而項目組其他人員不知道最終執行執行過rollback操作。大A寫了一個rollback方法,經過大量代碼,小d又寫了一個rollback操作,從而又拋出可一個新的異常:"There is no active transaction",沒開始一個激活的事務。
參考
http://www.jikexueyuan.com/course/653.html
http://stackoverflow.com/questions/38133260/is-it-necessary-to-rollback-if-commit-fails
http://stackoverflow.com/questions/2001698/if-an-php-pdo-transaction-fails-must-i-rollback-explicitely