I thought I would ask because I am unsure of the result of this operation not having worked with transactions much in a raw nature.
When an exception is thrown in PHP that stops execution, how is a DB transaction handled. Does it automatically rollback since the connection to the database is dropped from PHP or will a lock remain in place?
Pseudo Code
TX Begin
Select Balance
Logic in PHP
Exception
Rollback
Commit
Note: I know that best coding practice dictates that I rollback in the catch. This is just a behavioral question that I have wondered about.
To determine how MySQL handles transactions when a connection (session) is terminated, we have to consider whether autocommit
mode is enabled or not.
If a session that has autocommit disabled ends without explicitly committing the final transaction, MySQL rolls back that transaction.
Note, start transaction
does implicitly disable autocommit for the duration of the transaction:
With START TRANSACTION, autocommit remains disabled until you end the transaction with COMMIT or ROLLBACK. The autocommit mode then reverts to its previous state.
However, as @MarkBaker also pointed out, it still may be a good idea to explicitly roll back the transaction if an error was detected to make the point clear to all readers of the code. Remember, you yourself was not clear on how this exactly works and other php programmers may have the same question if they do not see an explicit rollback in your code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.