mysql transactions core php and cakephp


Today I came across mysql transactions here we will learn (mysql transactions core php and cakephp). it is really very important and in most cases there is no alternative to it. Most of the time we have to insert, update and delete in multiple tables while performing single process.
Do not consider this transaction the Bank transaction, this transaction is some thing else.

What is mysql transaction?

MySql or any other Database transaction is when we have to run multiple queries and we need to confirm all queries are executed successfully, even if one is failed than also revert other those are executed successfully. because than our data will not be consistent.
Example suppose we are developing student admission application, on admission process when we fill the form and click submit, we insert records into 3 tables, No.1- students table and No.2- we also insert a record in payments table. we have to make sure both insertions are done successfully. it will be our big loss if we admit a student in school and we do not charge admission fee. So we want our application to confirm both queried executed successfully else if first query executed successfully but second query got some error in this case also revert first query.

How we implement Transaction using PHP

it has 5 steps
1- try catch block so that we can throw error
2- Begin transaction
3- Inside try block run all queries and throw error on failure of each query
4- At end of try block commit the transaction, and redirect to success page
5- At catch block rollback the transaction and redirect to failure page with appropriate message

No we know what is Transaction and how to implement it, lets see code examples

Transactions example with Core PHP MySqli

it was so easy, now lets see transaction example with Cake PHP

Transactions example with Cake PHP

same logic and steps as defined above for core PHP, just syntax is changed

this was how to implement transaction using cake php

Important Note:
Using MySql the table engine type my be InnoDB, because MyISAM engine typed tables do not support transactions.

thats all


    Write a Reply or Comment

    Your email address will not be published. Required fields are marked *