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.
A transaction is a complete unit of operations where all actions either succeed together or fail together, ensuring data integrity.
PHP supports ACID transactions, including:
Use the mysqli_begin_transaction() function to start a transaction:
<?php
$conn = new mysqli("host", "username", "password", "database");
$conn->begin_transaction();
?>Once all operations in a transaction are complete, use mysqli_commit() to commit it:
<?php $conn->commit(); ?>
If any operation in a transaction fails, use mysqli_rollback() to roll it back:
<?php $conn->rollback(); ?>
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.