pdo begintransaction code example

Example 1: pdo transaction

<?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();

Example 2: php pdo transaction

$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;
}

Tags:

Php Example