PHP
MySQL
Transactions
Database
Programming Examples

PHP MySQL transactions examples

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

PHP, in combination with MySQL, is a classic duo for web development. PHP is a server-side scripting language that is known for its ease of use and integration with various databases. MySQL is one of the most popular database management systems (DBMS), and is renowned for its robustness, security, and ease of access. When using PHP and MySQL together, implementing transactions can greatly enhance data integrity and reliability.

Understanding Transactions

A transaction in a database is a sequence of operations performed that are treated as a single unit. For a transaction to be completed successfully, all the individual operations must succeed. If any of the operations fail, the transaction is considered incomplete, and any changes made during the transaction are usually rolled back, leaving the database in its previous state.

Transactions adhere to the ACID properties:

  • Atomicity: Ensures that all operations within a transaction are completed successfully. If not, the transaction is aborted at the point of failure, and all previous operations are reversed.
  • Consistency: Guarantees that the database transitions from one valid state to another, maintaining database invariants.
  • Isolation: Ensures that concurrent execution of transactions results in a system state that would be obtained if transactions were executed serially.
  • Durability: Once a transaction is committed, it remains so, even in the event of a system failure.

How PHP Implements Transactions with MySQL

To implement transactions in PHP with MySQL, we usually follow a pattern to begin the transaction, commit the transaction if successful, and rollback the transaction in case of any errors.

Basic Example of a Transaction

In this example, we perform two related actions: transferring funds between two accounts in a banking application.

php
1<?php
2// Create database connection
3$conn = new mysqli($servername, $username, $password, $dbname);
4
5// Check for connection errors
6if ($conn->connect_error) {
7    die("Connection failed: " . $conn->connect_error);
8}
9
10// Start the transaction
11$conn->begin_transaction();
12
13try {
14    $conn->query("UPDATE accounts SET balance = balance - 100 WHERE account_id = 1");
15    $conn->query("UPDATE accounts SET balance = balance + 100 WHERE account_id = 2");
16
17    // Commit the transaction if no errors
18    $conn->commit();
19    echo "Transaction Successful.";
20} catch (Exception $e) {
21    // Rollback the transaction in case of error
22    $conn->rollback();
23    echo "Transaction Failed: " . $e->getMessage();
24}
25
26// Close connection
27$conn->close();
28?>

Detailed Explanation

  1. Database Connection: A connection is established to the MySQL database using mysqli.
  2. Begin Transaction: A transaction is started using $conn->begin_transaction().
  3. Execute Queries: Two UPDATE statements try to debit and credit the respective accounts. These reflect the logical unit of work in a transaction.
  4. Commit Transaction: If all queries execute successfully, $conn->commit() finalizes the transaction, permanently saving all changes.
  5. Rollback Transaction: If any exception occurs during the execution of queries, $conn->rollback() is used to revert the database to its previous state, ensuring no partial updates.

Advanced Transaction Features

Savepoints

Savepoints allow for establishing checkpoints within a transaction. If an error occurs beyond the checkpoint, a partial rollback to the savepoint can occur.

php
1$conn->begin_transaction();
2try {
3    $conn->query("Query 1");
4    $conn->savepoint('SP1'); // Create Savepoint
5
6    $conn->query("Query 2");
7
8    // Assume something goes wrong here
9    if ($error_condition) {
10        $conn->rollback_to_savepoint('SP1'); // Rollback to savepoint
11    }
12
13    $conn->commit();
14} catch (Exception $e) {
15    $conn->rollback();
16}

Isolation Levels

MySQL supports different transaction isolation levels to handle various transaction consistency and throughput scenarios:

  • READ UNCOMMITTED
  • READ COMMITTED
  • REPEATABLE READ (default)
  • SERIALIZABLE

Setting isolation levels in PHP:

php
$conn->query("SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE");

Summary Table of Key Points

Key ConceptDescription
AtomicityEnsures that all operations in a transaction are completed or none at all.
ConsistencyGuarantees that transactions change the database from one valid state to another.
IsolationMaintains isolation between concurrent transactions to prevent data anomalies.
DurabilityEnsures that once a transaction is committed, it persists even in case of a failure.
SavepointsAllow for partial rollbacks within a transaction. Useful in complex transactional logic.
Isolation LevelsConfigurable isolation settings determine how transaction changes are isolated from other transactions. Types include READ COMMITTED and SERIALIZABLE.

Conclusion

Transactions are an essential concept in database management that ensure data integrity and consistency. By leveraging PHP and MySQL transactions effectively, developers can create applications that are both resilient and reliable, guaranteeing that any operations performed within the application do not leave the system in an inconsistent state, even in case of failures or exceptions. As web applications continue to grow in complexity, mastering transactions is becoming ever more critical for developers.


Course illustration
Course illustration

All Rights Reserved.