tags:

views:

36

answers:

2

Example:

// assume PDO instance here: $dbh

function beginTransaction() {
   global $dbh;
   $dbh->beginTransaction();
}

beginTransaction(); // no typo! called the function above!

$dbh->exec($sql1); // assume $sql1 is there
$dbh->exec($sql2); // assume $sql2 is there

$dbh->commit();

What I try to ask: Must a transaction be started and commited inside ONE scope, or can I span a transaction over a wide range of function and method calls? For me it would be logical that the called object doesn't care about the caller. But in Objective-C / Cocoa for example, a UIView animation block IS scope-aware! So I'm confused like a bird in a plane.

+2  A: 

One transaction can span over several functions and method calls : the transaction is happening on the database side, and not the PHP side.

A beginTransaction in PHP only send "BEGIN TRAN" (or an equivalent) to the database ; then, it's the database server who is responsible for the transaction -- PHP only send SQL commands.


As a sidenote : you are using this function in your example :

function beginTransaction() {
   $dbh->beginTransaction();
}

Just note (not sure if it's because you wrote a quick example, or if it's a real mistake) that $dbh will not exist in that function, unless you declare it as global, or pass it as a parameter -- see Variable scope in the manual.

Pascal MARTIN
thanks for that sidenote. I hacked the example quickly into the editor :)
openfrog
@openfrog : You're welcome :-) I wasn't sure, so I prefered putting a note, just in case :-)
Pascal MARTIN
A: 

The transaction is bound to the $dbh object, which is a PDO handle, I assume. It is independent of your current scope.

All database queries that are handled by $dbh will be part of that transaction if they are performed after calling $dbh->beginTransaction().

Techpriester