10

I'm using PHP's mysqli library. Database inserts and updates are always in a try-catch block. Success of each query is checked immediately (if $result === false), and any failure throws an exception. The catch calls mysqli_rollback() and exits with a message for the user.

My question is, should I bother checking the return value of mysqli_rollback()? If so, and rollback fails, what actions should the code take?

I have a hard time understanding how a rollback could fail (barring some atrocious bug in MySQL). And since PHP is going to exit anyway, calling rollback almost seems superfluous. I certainly think it should be in the code for clarity, but when PHP exits it will close the connection to MySQL and uncommitted transactions are rolled back automatically.

SDC
  • 14,192
  • 2
  • 35
  • 48
giskard22
  • 743
  • 1
  • 6
  • 15
  • 2
    If you're looking for a concrete example with realistic probability- Your php may execute on a different machine than the database runs on(eg, seperate database server). Network io has plenty of "works now but doesn't work the next second" scenarios. Of course it could happen with both on the same machine too, just much less likely. – goat Aug 24 '12 at 01:20
  • Interesting! Seems like the implications are the same in that scenario though: even if the rollback call fails, PHP's MySQL client session will end and rollback will happen. So maybe it's worth logging the error as an indicator of larger problems, but you still don't have to worry about data integrity. – giskard22 Aug 24 '12 at 17:41

2 Answers2

5

if rollback fails (connection failure for example), the changes will be rollbacked after the connection close anyway, so you don't need to handle the error. When you are in transaction, unless you have explicit commit (or you are running in autocommit mode, which means you have commit after each statement), the transaction is being roll back.

If a session that has autocommit disabled ends without explicitly committing the final transaction, MySQL rolls back that transaction.

The only case you would like to handle rollback error is if you are not exiting from your script, but starting a new transaction later, as starting transaction will implicitly commit the current one. Check out Statements That Cause an Implicit Commit

Maxim Krizhanovsky
  • 26,265
  • 5
  • 59
  • 89
  • That's what I figured. I wasn't aware of statements that cause implicit commit, so thank you! By the way, a better link for that information is probably [Statements That Cause an Implicit Commit](http://dev.mysql.com/doc/refman/5.1/en/implicit-commit.html) – giskard22 Aug 24 '12 at 17:47
0

mysqli_rollback can fail if you're not (never were) connected to the database. Depends on your error-handling before-hand.

EthanB
  • 4,239
  • 1
  • 28
  • 46