title: Calling SQL rollback on php exception
body: <p>Consider the following scenario:</p>
  
  <ul>
  <li>I open a new connection to MySQL, using mysqli extension</li>
  <li>I start a transaction</li>
  <li>I do some queries on the MySQL database and to some php computation</li>
  <li>Either MySQL or php may throw some exceptions</li>
  <li>I commit the transaction</li>
  </ul>
  
  <p>(pseudo) code:</p>
  
  <pre><code>$sql = new mysqli();
  ...
  { //some scope
      $sql-&gt;query("START TRANSACTION");
      ... 
      if (something)
          throw Exception("Something went wrong");
      ...
      $sql-&gt;query("COMMIT"); // or $sql-&gt;commit()
  } //leave scope either normally or through exception
  ...
  $sql-&gt;query( ... ); // other stuff not in transaction
  </code></pre>
  
  <p>If all the above is in some big <code>try catch</code> block (or perhaps even the exception is uncaught) the transaction will remain unfinished. If I then try to do some more work on the database, those actions will belong to the transaction.</p>
  
  <p>My question is: is there some possible mechanism that would permit me to automatically send <code>$sql-&gt;rollback()</code> when I leave the transaction-creating scope in an abnormal way?</p>
  
  <hr>
  
  <p>Some notes:</p>
  
  <ul>
  <li><a href="http://php.net/manual/en/mysqli.autocommit.php" rel="nofollow"><code>mysqli::autocommit</code></a> is not the same as a transaction. It is just a setting for autocommit you turn on or off. Equivalent to MySQL <code>SET autocommit</code>.</li>
  <li><a href="http://php.net/manual/en/mysqli.begin-transaction.php" rel="nofollow"><code>mysqli::begin_transaction</code></a> is not documented and I don't know what is its precise behavior. Will it call <code>rollback</code> when the <code>mysqli</code> object dies for example?</li>
  </ul>