By default, PostgreSQL uses the auto-commit mode. This means that for every statement that the application issues, PostgreSQL commits it automatically.
To turn off the auto-commit mode in PHP, you call the beginTransaction() method of the PDO object. By doing this, the change to the database is made only when the commit() method of the PDO object is called.
If there is an exception or error, you can cancel the change using the rollback() method of the PDO object.
The typical usage of the transaction in PHP PDO is as follows:
PostgreSQL PHP transaction example
We’ll create the following tables for the demonstration:
accounts: stores the account information such as first name, last name
plans: stores the plan information for the account such as silver, gold, and platinum.
account_plans : stores the plan for each account with the effective date.
The following CREATE TABLE statements create the three tables:
The following INSERT statement inserts some sample data into the plans table.
When creating an account, you need to assign a plan that can be silver, gold, or platinum. To ensure that an account always has at least one plan at a time, you use the transaction API in PDO.
The following addAccount() method performs two main steps:
First, insert an account into the accounts table and return the account id.
Then, assign the account a specific plan by inserting a new row into the account_plans table.
At the beginning of the method, you call the beginTransaction() method of the PDO object to start the transaction.
If all the steps succeed, you call the commit() method to save the changes. If an exception occurs in any step, you roll back the changes by calling the rollback() method in the catch block:
The addAccount() method uses two other private methods: insertAccount() and insertPlan() as shown in the following:
To test the AccountDB class, you use the following code in the index.php file.
How it works.
First, connect to the PostgreSQL database.
Second, insert three accounts with silver, gold, and platinum levels.
Third, try to insert one more account but with a plan ID that does not exist in the plans table. Based on the input, the step of assigning the plan to the account fails which causes the whole transaction to be rolled back.
The following shows the output of the index.php file:
If you query the data in the accounts and account_plans tables, you will see only three rows inserted in each table:
Summary
Use the beginTransaction() method of the PDO object to start a transaction.
Use the commit() method to apply the changes to the database and rollback() method to undo the changes.