If an PHP PDO transaction fails, must I rollback() explicitely?

非 Y 不嫁゛ 提交于 2020-01-01 10:04:16

问题


I've seen an code example where someone does a

$dbh->rollback();

when there occurs an PDOException. I thought the database will rollback automatically in such a case?


回答1:


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.


Still, I (well, almost) always commit or rollback explicitly the transactions I open, so :

  • There is not risk of an error (like commiting "by mistake" later in the script)
  • 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 ?"


The DB engine doesn't "see" the PDOException : it is thrown by PHP under various conditions -- but the database doesn't rollback anything by itself :

  • either a transaction is commited
  • or it's rolled-back
  • or it's not explicitly commited nor rolled-back -- which means it's not commited -- which means what's been modified is not "really" modified


来源:https://stackoverflow.com/questions/2001698/if-an-php-pdo-transaction-fails-must-i-rollback-explicitely

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!