I think the question itself is pretty clear. The code is 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 INTO 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 a database transaction. The error message is : ".$e->getMessage(); $PDO->rollBack(); die(); } ?>
Even if I roll back the transaction inside the catch block, the data is still inserted into the database. Why?
EDIT
I am adding the following few lines from the documentation for further clarification -
Unfortunately, not every database supports transactions, so the PDO needs to run in the so-called auto-commit mode when the connection is first opened. Automatic commit mode means that each request you make is its own implicit transaction, if the database supports it, or not if the database does not support transactions. If you need transactions, you should use the PDO :: beginTransaction () method to initiate one. If the underlying driver does not support transactions, a PDOException is thrown (regardless of handling configuration errors: this is always a serious error condition). When you are located you can use PDO :: commit () or PDO :: rollBack () to complete this, depending on the success of the code that you run during the transaction.
In addition, the following lines from this page are
bool PDO::beginTransaction ( void )
Disables autosave mode. Although autosave mode is disabled, the changes made to the database through an instance of the PDO object are not until you complete the transaction by calling PDO :: commit (). A call to PDO :: rollBack () will roll back all changes to the database and return the connection to autosave.
Some databases, including MySQL, automatically issue implicit COMMITs when a database definition language (DDL) statement such as DROP TABLE or CREATE TABLE is issued inside a transaction. implicit COMMIT will not allow you to undo any other changes within the transaction boundary.
php pdo
MD Sayem Ahmed
source share