Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO Transactions & function calls

Can function calls occur within a PDO transaction block? This is simplified code (using MySql database)...

try{  
  $db->beginTransaction();  

  // call to function that creates user
  $user_id = create_user();  

  // call to function that creates company      
  $company_id = create_company();

  // call to function to link user & company
  add_user_to_company($user_id, $company_id);

  $db->commit();  
}

If this can't happen using transactions, what is the recommended strategy?

like image 886
csi Avatar asked May 08 '12 14:05

csi


People also ask

What is a transaction in PDO?

Introduction to PHP PDO transaction It means that the changes made to the database via the PDO object won't take effect until you call the PDO::commit() method. To commit a transaction, you call the PDO::commit() method: $pdo->commit(); Code language: PHP (php)

Why is PDO used?

PDO provides a data-access abstraction layer, which means that, regardless of which database you're using, you use the same functions to issue queries and fetch data. PDO does not provide a database abstraction; it doesn't rewrite SQL or emulate missing features.

What are PHP transactions used for?

Transaction means to complete several actions of a group without any interruption and if something wrong happens then revert everything to the initial stage. In SQL, successful transaction means that all SQL statements has been executed successfully.

What does PDO stand for MySQL?

PDO (PHP Data Objects) is a general database abstraction layer with support for MySQL among many other databases. It provides prepared statements, and significant flexibility in how data is returned.


1 Answers

Unless any of those function calls attempts to open or commit a transaction themselves, or use a different connection than the one stored in $db, yes it should work just fine. The PDO object (or the RDBMS for that matter) doesn't know or care whether you are calling other functions in PHP. All it knows is if the action is taking place on the same open connection as the one opened in $db. We assume that those functions either receive $db as a parameter or access it globally.

Remember that although PDO keeps track of transaction state (exposed through PDO::inTransaction()), it is really the RDBMS which is managing the transaction state, not PDO or the PHP application code. If, a function attempts to open a new transaction before the previous one was committed, MySQL's documented behavior is to auto-commit the previous transaction since it does not support transaction nesting.

So just be sure your additional function calls are not attempting to change the transaction state.

like image 50
Michael Berkowski Avatar answered Oct 23 '22 09:10

Michael Berkowski