Ready to watch this entire course?
Become a member and get unlimited access to the entire skills library of over 4,971 courses, including more Developer and personalized recommendations.Start Your Free Trial Now
- View Offline
- Connecting to a database with PDO or MySQLi
- Fetching a result set
- Executing simple non-SELECT queries
- Sanitizing user input
- Binding input and output values
- Passing an array of values to the execute() method
- Working with advanced PDO fetch methods
- Executing a MySQLi transaction
- Freeing resources that are no longer needed
- Submitting multiple queries
- Creating an instance of a class from a result set
Skill Level Intermediate
Transactions allow you to treat a series of SQL queries as a single unit that's executed only if all parts of it succeed. Let's use a simple example of transferring money to see how to implement a transaction in MySQL Improved. This is mysqli_transaction.php, which you can find in the chapter six 06_04 folder of the exercise files. On line four, a select query selects name and balance from a table called savings. And in the body of the page, an HTML table displays the result set. So let's load this into a browser and see what we've got. There are just two accounts in this table, one for John White, the other for Jane Black. Both have $1,000 in their balance.
We're going to use a transaction to transfer $200 from John's account to Jane's. So let's get back to the code. And we need to scroll back up to the top. And to save time, I'm going to paste in some prepared statements to set up the transfer. The code is in transfer.txt, which you can find in the exercise files for this video, and the new code needs to go before this select query. So we'll add in some extra space up there, then paste in the code. On lines five, six and seven, we initialize a few variables, one for the amount, the other two for the account names. Then there are a couple of SQL update queries. The first one deducts the amount from the balance of whoever's paying and the second one adds the amount to the balance whoever is receiving the amount.
The rest of the code that we've pasted in initializes a couple of statements. One is called pay, the other one is called receive, and values of the amount and the name of the account are bound to the placeholders. So we're now ready to begin our transaction. We'll scroll up. We need the transaction to go before this select query. And there are a couple of ways in MySQLi to begin a transaction. One of them is to use the begin_transaction method. You call that on the database connection object, and this does exactly what it says.
The only problem is it didn't become available until PHP 5.5. So if you're using an earlier version of PHP, this won't work. No problem. Let's just comment that out. The alternative way to do it is to disable auto-commit mode in MySQL and you do that also with the database connection object and you call the autocommit method, and you pass it false as an argument.
That simply turns off auto-commit mode and has the effect of beginning a transaction. The first part of the transaction is to execute the pay prepared statement. So, pay, and we need to execute that. We also need to make sure that it succeeds. We need to make sure that the amount has been deducted from the account. We can find that out by using the affected_rows property. Although we're using a prepared statement, the affected_rows property is a property of the database object. So we'll have a conditional statement. If not, then the database object affected_rows. If it's failed, we need to roll back, and we roll back using the rollback method on the database object.
So, db rollback. And if we have rolled back, we need an error message to explain what the problem was. The affected_rows property will be 1 if the update succeeded or it'll be 0 if it failed. If it succeeded, we need to continue with the second part of the transaction, so we'll do that in an else block. We then execute the receive prepared statement. We need to check that that also succeeded. We do that in exactly the same way by checking the affected_rows property.
So if we just copy all of that, and then paste it inside the else block, and we need to just change this from payer's account to payee's account. If everything went okay, we can then commit our transaction. And you commit the transaction using the commit method on the database object. So, db commit. So let's just scroll up a bit and see what we have done. We've begun the transaction by turning the auto-commit mode on MySQL to false.
Then we execute the first prepared statement and check the affected_rows property. If it failed, we use the database object to roll back the transaction. Otherwise, we continue with a second part. We make another check exactly the same. If everything went okay, we finally use the commit method of the database object to complete the transaction. So if we save that page and go back to the browser and refresh the page, Jane Black's account has gone up to $1,200.
But let's see what happens if parts of the transaction fails. So go back to the code and we'll go up to the top. And we'll make Jane Black Jane Brown. And there is no Jane Brown in our table. So, if we go back to the browser and refresh the page, transaction failed. Couldn't update Jane Brown's account and John White's account remains at $800. The transaction fails because there's no account for Jane Brown.
That's why it's so important to check the affected_rows property. The transaction will initially have deducted $200 from John's account, but it then rolled back when it failed to update Jane Brown's account. If you check to see whether the execute method returns true, you'll get what appears to be a false positive. This SQL on line nine is perfectly valid, so it's executed correctly. But without a matching name, it doesn't update any records, so affected_rows is 0, which equates to false.
So that's how you perform a transaction in MySQLi. One important point to remember is that all tables involved in a transaction must use the InnoDB engine. If you use MyISAM tables, the rollback will be silently ignored.