PDO beginTransaction and commit

PDO::beginTransaction — Initiates a transaction.

Some databases, including MySQL, automatically issue an implicit COMMIT when a database definition language (DDL) statement such as DROP TABLE or CREATE TABLE is issued within a transaction. The implicit COMMIT will prevent you from rolling back any other changes within the transaction boundary.

Example #1 Roll back a transaction

<?php

$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');

/* Begin a transaction, turning off autocommit */

$db->beginTransaction();

/* Change the database schema and data */

$stmt = $db->exec("DROP TABLE fruit");

$stmt = $db->exec("UPDATE dessert SET name = 'hamburger'");

/* Recognize mistake and roll back changes */

$db->rollBack();

/* Database connection is now back in autocommit mode */

?>
You can generate problems with nested beginTransaction and commit calls.
beginTransaction() 

do imprortant stuff 

call method 
    beginTransaction() 
    basic stuff 1 
    basic stuff 2 
    commit() 

do most important stuff 

commit() 

It  is dangerous since you could close your transaction too early with the nested commit().

There is no need to mess you code and pass like a bool which indicate if transaction is already running. You could just overload the beginTransaction() and commit() in your PDO wrapper like this:


Loading ...

Related Results :

  1. PDO beginTransaction and commit
Note :
  • Related Posts are generally User Blog posts.
  • or Other tutorials from other networks of w3clan.com.
  • Any registered user can create related posts based on search term tags.

About the Author