Skip to content

Instantly share code, notes, and snippets.

@macloo
Last active January 26, 2016 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macloo/55a057b952c3d85dfe6d to your computer and use it in GitHub Desktop.
Save macloo/55a057b952c3d85dfe6d to your computer and use it in GitHub Desktop.
Doing transactions in PHP for MySQL
<?php
// $conn comes from a separate database connection file
// this is a partial, nonworking file
try {
// Let's begin a transaction
mysqli_begin_transaction($conn, MYSQLI_TRANS_START_READ_ONLY);
// There can be a set of queries
// If any one fails, an exception should be thrown
mysqli_query($conn, "SELECT first_name, last_name FROM actor LIMIT 1");
// If we arrive here, it means that no exception was thrown
// i.e. no query has failed, and we can commit the transaction
mysqli_commit($conn);
} catch (Exception $e) {
// An exception has been thrown
// We must rollback the transaction (undo it)
mysqli_rollback($conn);
}
mysqli_close($conn);
?>