Current Location: Home> Latest Articles> PHP Transactions Explained: Principles, ACID Features, and Usage

PHP Transactions Explained: Principles, ACID Features, and Usage

M66 2025-10-25

Overview of PHP Transactions

A transaction is an atomic operation unit in a database—it either completes entirely or rolls back completely. PHP supports transaction operations, ensuring the security and consistency of database actions.

What is a Transaction?

A transaction is a complete unit of operations where all actions either succeed together or fail together, ensuring data integrity.

ACID Transactions in PHP

PHP supports ACID transactions, including:

  • Atomicity: All operations in a transaction succeed or all are rolled back.
  • Consistency: The database remains in a consistent state after the transaction.
  • Isolation: Transactions are isolated from each other.
  • Durability: Once committed, the transaction changes are permanent.

Starting a Transaction

Use the mysqli_begin_transaction() function to start a transaction:

<?php
$conn = new mysqli("host", "username", "password", "database");
$conn->begin_transaction();
?>

Committing a Transaction

Once all operations in a transaction are complete, use mysqli_commit() to commit it:

<?php
$conn->commit();
?>

Rolling Back a Transaction

If any operation in a transaction fails, use mysqli_rollback() to roll it back:

<?php
$conn->rollback();
?>

Transaction Example

The following example demonstrates how to use transactions in PHP:

<?php
$conn = new mysqli("host", "username", "password", "database");

$conn->begin_transaction();

$sql = "UPDATE users SET balance = balance + 100 WHERE id = 1";
$conn->query($sql);

$sql = "UPDATE accounts SET balance = balance - 100 WHERE id = 2";
$conn->query($sql);

$conn->commit();
?>

In this example, if the second update fails, the transaction will roll back, and neither update will be applied to the database, ensuring data integrity and consistency.