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

--------------------------------------------------------------------------
The program calls the `begin_transaction()` 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()`.


`mysqli` example:
```
<?php
  mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

  try {
    $mysqli = new mysqli("127.0.0.1", "root", "", "test", 4000);
    if ($mysqli->connect_errno) {
      die("Error connecting: " . $mysqli->connect_error);
    }
    print "Connection established.<p>";
    $mysqli->query("DROP TABLE IF EXISTS t_php");
    $mysqli->query("CREATE TABLE t_php (id BIGINT PRIMARY KEY AUTO_RANDOM, name VARCHAR(20), buffered_by_default char(1))");
    $num = $mysqli->query("INSERT INTO t_php (name)"
      . " VALUES "
      . "('mysqli'), ('PDO_MySQL')");
    echo $num . " rows(s) inserted.<p>";

    try {
      $mysqli->begin_transaction();
      echo "Transaction begin." . "<p>";
      $mysqli->query("UPDATE t_php SET buffered_by_default = 'Y' WHERE name = 'mysqli'");
      $mysqli->query("UPDATE t_php SET buffered_by_default = 'N' WHERE name = 'PDO_MySQL'");
      $mysqli->commit();
      echo "Transaction end." . "<p>";
    } catch (Exception $e) {
      print("Transaction failed, error goes here:<p>");
      print($e->getMessage() . "<p>");
      try {
        $mysqli->rollback();
      } catch (Exception $er) {
        print("Unable to roll back. Error was:<p>");
        print($er->getMessage() . "<p>");
      }
    }
    $res = $mysqli->query("SELECT name, buffered_by_default FROM t_php");
    if (!$res) {
      echo "Query failed: " . $mysqli->error;
    } else {
      foreach ($res as $row) {
        printf("Name: %s, Buffered Result Set by Default: %s<p>", $row['name'], $row['buffered_by_default']);
      }
    }
  } catch (Exception $e) {
    die($e->getMessage());
  }

  ?>
```
