# Typical Workflow for Using Transaction: `PDO_MySQL`
+ Use **`try-catch`** to execute transaction  
  + **`try`** 
    + Begin transaction: **`$dbhandle->beginTransaction()`**
    + Execute **`DML`**  
    + Commit: **`$dbhandle->commit()`**
  + **`catch`** 
    + **`try`** 
      + What to do after `DML` fails
      + Rollback: **`$dbhandle->rollback()`** 
    + **`catch`** 
      + Failed to process rollback

------------------------------------------------------------
The program calls the `beginTransaction()` method to start a transaction. 

The `DML` statements execute in a transaction. If they are successful, they are persisted to the database by the `commit()` method.

If either of the `UPDATE` statements in the first try block fails, the program raises an exception and calls `rollback()`.


PDO_MySQL example:
```php
  <?php
  echo "PDO_MySQL Example - Transaction Control" . "<p>";

  try {
    $dsname = "mysql:host=127.0.0.1;port=4000;dbname=test";
    $dbhandle = new PDO($dsname, "root", "");
    print "Connection established.<p>";
    $dbhandle->exec("DROP TABLE IF EXISTS t_php");
    $dbhandle->exec("CREATE TABLE t_php (id BIGINT PRIMARY KEY AUTO_RANDOM, name VARCHAR(20), buffered_by_default char(1))");
    $num = $dbhandle->exec("INSERT INTO t_php (name)"
      . " VALUES "
      . "('mysqli'), ('PDO_MySQL')");
    echo $num . " rows(s) inserted.<p>";

    try {
      $dbhandle->beginTransaction();
      echo "Transaction begin." . "<p>";
      $dbhandle->exec("UPDATE t_php SET buffered_by_default = 'Y' WHERE name = 'mysqli'");
      $dbhandle->exec("UPDATE t_php SET buffered_by_default = 'N' WHERE name = 'PDO_MySQL'");
      $dbhandle->commit();
      echo "Transaction end." . "<p>";
    } catch (Exception $e) {
      print("Transaction failed, error goes here:<p>");
      print($e->getMessage() . "<p>");
      try {
        $dbhandle->rollback();
      } catch (Exception $er) {
        print("Unable to roll back. Error was:<p>");
        print($er->getMessage() . "<p>");
      }
    }
    $dbhandle->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
    $statementhandle = $dbhandle->query("SELECT name, buffered_by_default FROM t_php");
    while ($row = $statementhandle->fetch(PDO::FETCH_ASSOC)) {
      printf("Name: %s, Buffered Result Set by Default: %s<p>", $row['name'], $row['buffered_by_default']);
    }
    print "Connection terminated.";
  } catch (PDOException $err) {
    die($err);
  }

  ?>
```
