pdo transaction
snippet in php

pdo transaction

user1902

<?php
/* Begin a transaction, turning off autocommit */
$dbh->beginTransaction();

try	{
	/* Change the database schema and data */
    $sth = $dbh->exec("DROP TABLE fruit");
    $sth = $dbh->exec("UPDATE dessert
        SET name = 'hamburger'");
}
catch(Exception $e){
  /* Recognize mistake and roll back changes */
  $dbh->rollBack();
}
/* Commit changes */
$dbh->commit();

php pdo transaction

user5642

$pdo = new PDO(
    $dsn, 
    $username, 
    $password, 
    array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
);

try {
    $statement = $pdo->prepare("UPDATE user SET name = :name");

    $pdo->beginTransaction();

    $statement->execute(["name"=>'Bob']);
    $statement->execute(["name"=>'Joe']);

    $pdo->commit();
} 
catch (\Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollback();
        // If we got here our two data updates are not in the database
    }
    throw $e;
}