Last active
January 26, 2016 14:31
-
-
Save macloo/55a057b952c3d85dfe6d to your computer and use it in GitHub Desktop.
Doing transactions in PHP for MySQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sources:
http://stackoverflow.com/questions/2708237/php-mysql-transactions-examples
http://php.net/manual/en/mysqli.begin-transaction.php
http://php.net/manual/en/mysqli.rollback.php
Handling exceptions: try / catch
http://php.net/manual/en/language.exceptions.php