The key part is to set PDO in exception mode , while trying to catch only try to roll back is not required. So your code is fine, you donβt need to change it if all you need is a rollback on failure, if you have this line somewhere:
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
If the script fails, the connection is closed and mysql will be happy to cancel the transaction for you.
If you still want a manual rollback, you have to do it right, not like the other answers say. Make sure that
- you are catching an
Exception , not a PDOException , since it doesn't matter which particular exception aborts the execution - you throw an exception after rolling back to receive a notification about the problem
- also that the table engine supports transactions (that is, for Mysql it should be InnoDB, not MyISAM).
This checklist is taken from my article , which may be useful in this or many other aspects.
source share