php - Why the following PDO transaction is committing? -


i think question pretty self-explanatory. code given below -

<?php     $pdo = null;     $pdo_dsn = 'mysql:host=localhost;dbname=pdo_test';     $pdo_persistence = array( pdo::attr_persistent => true );     $db_user = 'root';     $db_pass = '';     $db_query = "insert person(name, address)                     values ('mamsi mamsi', 'katabon')";      try     {             $pdo = new pdo($pdo_dsn, $db_user, $db_pass,                                $pdo_persistence);     }     catch(pdoexception $e)     {             echo "error occured: ". $e->getmessage();             die();     }      $pdo->setattribute(pdo::attr_errmode,                             pdo::errmode_exception);     $pdo->setattribute(pdo::attr_autocommit, false);      try     {             $pdo->begintransaction();             $pdo->exec($db_query);              throw new pdoexception('generated exception');              $pdo->commit();     }     catch(pdoexception $e)     {             echo "an error occured while doing database transaction.              error message : ".$e->getmessage();              $pdo->rollback();             die();     } ?> 

even if rolling transaction inside catch block, data still being inserted database. why?

edit

i adding following few lines documentation further clarification -

unfortunately, not every database supports transactions, pdo needs run in known "auto-commit" mode when first open connection. auto-commit mode means every query run has own implicit transaction, if database supports it, or no transaction if database doesn't support transactions. if need transaction, must use pdo::begintransaction() method initiate one. if underlying driver not support transactions, pdoexception thrown (regardless of error handling settings: serious error condition). once in transaction, may use pdo::commit() or pdo::rollback() finish it, depending on success of code run during transaction.

also, following lines this page -

bool pdo::begintransaction  ( void  ) 

turns off autocommit mode. while autocommit mode turned off, changes made database via pdo object instance not committed until end transaction calling pdo::commit(). calling pdo::rollback() roll changes database , return connection autocommit mode.

some databases, including mysql, automatically issue implicit commit when database definition language (ddl) statement such drop table or create table issued within transaction. implicit commit prevent rolling other changes within transaction boundary.

you should check using innodb database type. myisam not support transactions.


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -