Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Executing a transaction

From: Accessing Databases with Object-Oriented PHP

Video: Executing a transaction

{QTtext}{width:960}{textColor:65280,65280,65280}{justify:center}{timescale:1000}{backColor:0,0,0}{plain}{font:Verdana}{size:20} Transactions allow you to treat a series of SQL queries as Now that we've begun the transaction, we can execute the first prepared statement.

Executing a transaction

Transactions allow you to treat a series of SQL queries as a single unit that's executed only if all parts of it succeeds. If we scroll down a little on line 27 is a loop that loops over Let's use a very simple example to see how transactions work. a query that selects the name and balance values from a table called savings. This is pdo_transaction.php which you can find in the Chapter 3, 03_06 folder of the exercise files.

Then on lines 29 and 30 those values are displayed. So, let's just take a quick at that in a browser. It's a very small savings bank we've got here, just two accounts. One for John White, one for Jane Black. They've both got a $1,000 in their account. We'll use a transaction to transfer $200 from John's account to Jane's. So, let's go back to the editing program. And to save some time, I'm going to paste in some prepared statements to setup the transfer.

in some prepared statements to setup the transfer. The code is in transfer.txt, which you can find in the exercise files for this video. Needs to go straight after the database collection, create a new line on line four and paste in that code. Let's just take a very quick look at the code that we've pasted in. Lines five, six and seven, setup three variables, one for the amount and two for the names of the different accounts.

Then on lines eight and nine are two prepared statements that use named parameters. The first one deducts the amount from the balance while the second one adds it. And both statements are prepared, and the values are bound to the placeholders. So we now need to begin the transaction. And to do that, all you need to do is to call the begin transaction method on the database connection object.

So let's add in some space. Now that we've begun the transaction, we can execute the first prepared statement. The first one is called pay. So we just call the execute method. And we need to check whether it was executed successfully. We can do that using the row count method. When we looked at the row count method with a select query in the previous chapter, it didn't work with SQLite.

However, when used with an insert, update, or delete statement, row count always returns the number of records affected. So, if this is executed correctly and the amount is deducted, row count will return one, which equates to true. If it fails, row count will return 0, which equates to false. So, we can use row count as our condition. So, if not pay row count.

We know that it has failed and if it has failed we need to roll back. So this is done on the database connector. Just call the roll back method. And if we have rolled back, we need to have an error message to explain what the problem was. So, we'll store that as error. But assuming that the first prepared statement was executed correctly, we can then continue with the second one. So we do that in an else block. The second prepared statement is called receive.

We just execute that, and again we need to check whether it was executed correctly. And we use exactly the same structure. If row count is 0, we know that it's failed. If it's 1, we know that it's succeeded. So let's very quickly copy that. And we can paste that inside this else block, and it's the receive row count that we're checking this time. We roll back if it fails, and we have put the correct message that it's the payee's balance that we weren't able to update.

But if it does succeed, if row count is one, we put in another else block here, and we just commit the transactions. So that's how a transaction works. You start off by calling the begin transaction method on the database object. You execute the first part of the transaction. If it fails you use the rollback method, otherwise you execute the next part of the transaction. If that fails again, you roll back.

But if everything has gone fine, you then use the commit method and that changes everything in the database and updates it. So if we save that. And we go back to the browser. If we refresh the page, John White's balance has gone down to $800 and Jane Black's has gone up to $1,200. So the transaction has worked fine.

But let's try to transfer John's hard earned cash to someone without an account. So, let's go back here and right at the top instead of transferring to Jane Black, we'll transfer to Jane Brown. And there is no Jane Brown in our savings table.

And there is no Jane Brown in our savings table. So, if we go back to the browser and refresh. This time we got a message, transaction failed. Could not update Jane Brown's balance. We can see that John White, $200, hasn't been taken out of his account. So, the transaction has kept everything nice and safe.

Make sure the test for failure produces valid results. For example, when we changed the payee to Jane Brown, the SQL was perfectly valid so it didn't produce an error. But nor did it update the table because there's no record for Jane Brown. You must use a database that supports transactions. PDO doesn't simulate transactions for you. Although, MySQL supports transactions with the inner db engine.

MyISAM tables silently ignore transactions commands. PDO doesn't simulate transactions for you. Although, MySQL supports transactions with the inner db engine. So, you'll get no warning. MySQL and some other databases automatically create queries that commits data definition language. Such as drop table or create table in the middle of transaction. There is no way of undoing such automatic commits

Show transcript

This video is part of

Image for Accessing Databases with Object-Oriented PHP
Accessing Databases with Object-Oriented PHP

47 video lessons · 1904 viewers

David Powers
Author

 
Expand all | Collapse all
  1. 13m 33s
    1. Welcome
      1m 4s
    2. What you should know before watching this course
      2m 8s
    3. Using the exercise files
      4m 56s
    4. Setting SQLite permissions
      1m 11s
    5. A quick primer on using PHP objects
      4m 14s
  2. 10m 12s
    1. Overview of PHP database APIs
      4m 5s
    2. Using prepared statements
      4m 24s
    3. Using transactions
      1m 43s
  3. 48m 57s
    1. Creating a database source name
      2m 3s
    2. Connecting to a database with PDO
      7m 27s
    3. Looping directly over a SELECT query
      3m 49s
    4. Fetching a result set
      8m 3s
    5. Finding the number of results from a SELECT query
      7m 14s
    6. Checking if a SELECT query contains results
      3m 32s
    7. Executing simple non-SELECT queries
      6m 2s
    8. Getting error messages
      7m 17s
    9. Using the quote() method to sanitize user input
      3m 30s
  4. 39m 51s
    1. Binding input and output values
      2m 36s
    2. Using named parameters
      9m 51s
    3. Using question marks as anonymous placeholders
      2m 35s
    4. Passing an array of values to the execute() method
      5m 20s
    5. Binding results to variables
      7m 53s
    6. Executing a transaction
      6m 54s
    7. Closing the cursor before running another query
      4m 42s
  5. 21m 20s
    1. Generating an array from a pair of columns
      2m 44s
    2. Setting an existing object's properties with a database result
      4m 42s
    3. Creating an instance of a specific class with a database result
      6m 1s
    4. Reusing a result set
      7m 53s
  6. 38m 14s
    1. Connecting to a database with MySQLi
      5m 57s
    2. Setting the character set
      1m 57s
    3. Submitting a SELECT query and getting the number of results
      4m 4s
    4. Fetching the result
      7m 35s
    5. Rewinding the result for reuse
      3m 20s
    6. Handling non-SELECT queries
      5m 27s
    7. Getting error messages
      5m 47s
    8. Sanitizing user input with real_escape_string()
      4m 7s
  7. 27m 49s
    1. Initializing and preparing a statement
      4m 17s
    2. Binding parameters and executing a prepared statement
      5m 55s
    3. Binding output variables
      5m 6s
    4. Executing a MySQLi transaction
      7m 5s
    5. Dealing with "commands out of sync" in prepared statements
      5m 26s
  8. 24m 7s
    1. Buffered and unbuffered queries
      4m 19s
    2. Using real_query()
      6m 1s
    3. Freeing resources that are no longer needed
      2m 31s
    4. Submitting multiple queries
      6m 41s
    5. Creating an instance of a class from a result set
      4m 35s
  9. 3m 31s
    1. PDO and MySQLi compared
      3m 31s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Accessing Databases with Object-Oriented PHP.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.