I have just successfully attempted using beginTransaction() to execute my sql statements in my project using PHP. I have an array of items need to be written to the database, and each item must be validated against something before getting stored. One of the good things about turning off the auto-commit behaviour of a database is you can rollback the whole transaction if something goes wrong in the middle. In my project, if one item is invalid, the whole array should not be recorded in the database, which is why I chose to use this approach.
Now I am just wondering if this really is a better way in terms of performance? Because even if the last item in the array is validated, I still need to manually commit() the previous execution. Does commit repeat the sql execution?
The only advantage I can think of right now is you only need to do one loop instead of two if you want to validate them all (assuming all items are valid) and then write each of them.
Commit does not repeat SQL execution.
Typically, when working in a transactional, whenever you execute an INSERT/UPDATE/DELETE statement, the database takes a copy of the records/data pages to a transaction log, and then executes the actual record changes.
If anybody else tries to access those records/data pages during the course of your transaction, they will be redirected to the copy in the transaction log.
Then, when you execute the commit, the data in the database itself is already updated, and all the server needs to do is delete the transaction log.
If you rollback rather than commit, then the database server backtracks through the transaction log, restoring all the records/data pages that you have updated to their original state, deleting each transaction log entry as it goes.
Therefore, a rollback is an overhead, because the database server has to restore the data to its pre-transaction state.