Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

PHP Dictionary

  1. Home
  2. PHP Dictionary
  3. PDO::beginTransaction() / commit() / rollBack()

PDO::beginTransaction() / commit() / rollBack() Since: PHP 5(2004)

A transaction is a mechanism that executes multiple SQL operations as a single unit. If an error occurs partway through, all operations are rolled back to preserve data integrity.

Syntax

// Starts a transaction.
$pdo->beginTransaction();

// Commits the transaction.
$pdo->commit();

// Rolls back the transaction.
$pdo->rollBack();

// Checks whether a transaction is currently active.
$pdo->inTransaction();

Method List

MethodDescription
PDO::beginTransaction()Starts a transaction. Auto-commit is disabled, and changes are not saved until you call commit() or rollBack().
PDO::commit()Commits all operations in the transaction and applies them to the database.
PDO::rollBack()Cancels all operations in the transaction and reverts the database to its state before the transaction began.
PDO::inTransaction()Returns true if a transaction is currently active.

Sample Code

<?php
// Basic transaction: transfer funds between accounts.
try {
	$pdo->beginTransaction();

	// Deduct the amount from the sender's balance.
	$stmt = $pdo->prepare("UPDATE accounts SET balance = balance - :amount WHERE id = :id");
	$stmt->execute([':amount' => 10000, ':id' => 1]);

	// Add the amount to the recipient's balance.
	$stmt = $pdo->prepare("UPDATE accounts SET balance = balance + :amount WHERE id = :id");
	$stmt->execute([':amount' => 10000, ':id' => 2]);

	$pdo->commit(); // Commit if all steps succeeded.
	echo "Transfer completed successfully.";
} catch (PDOException $e) {
	$pdo->rollBack(); // Roll back everything if an error occurred.
	echo "Transfer failed: " . $e->getMessage();
}

// Order processing: insert an order and update inventory atomically.
try {
	$pdo->beginTransaction();

	// Insert the order.
	$stmt = $pdo->prepare("INSERT INTO orders (user_id, product_id, quantity) VALUES (:user_id, :product_id, :qty)");
	$stmt->execute([':user_id' => 1, ':product_id' => 100, ':qty' => 2]);
	$orderId = $pdo->lastInsertId();

	// Reduce the stock.
	$stmt = $pdo->prepare("UPDATE products SET stock = stock - :qty WHERE id = :id AND stock >= :qty");
	$stmt->execute([':qty' => 2, ':id' => 100]);

	// Roll back if stock was insufficient.
	if ($stmt->rowCount() === 0) {
		$pdo->rollBack();
		echo "Insufficient stock.";
	} else {
		$pdo->commit();
		echo "Order ID: " . $orderId . " has been placed.";
	}
} catch (PDOException $e) {
	if ($pdo->inTransaction()) {
		$pdo->rollBack(); // Only roll back if a transaction is still active.
	}
	echo "Order processing failed: " . $e->getMessage();
}

// Check transaction state with inTransaction().
var_dump($pdo->inTransaction()); // Outputs bool(false) when outside a transaction.
$pdo->beginTransaction();
var_dump($pdo->inTransaction()); // Outputs bool(true) during an active transaction.
$pdo->rollBack();

// Use a transaction to speed up bulk inserts.
$users = [
	['name' => 'Alice', 'email' => 'alice@example.com'],
	['name' => 'Bob',   'email' => 'bob@example.com'],
	['name' => 'Carol', 'email' => 'carol@example.com'],
];

try {
	$pdo->beginTransaction();
	$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
	foreach ($users as $user) {
		$stmt->execute([':name' => $user['name'], ':email' => $user['email']]);
	}
	$pdo->commit(); // A single commit at the end greatly improves performance.
	echo count($users) . " users have been registered.";
} catch (PDOException $e) {
	$pdo->rollBack();
	echo "Bulk insert failed: " . $e->getMessage();
}

Overview

A transaction is a mechanism for executing multiple database operations atomically. When updating multiple tables — such as in a fund transfer — skipping transactions can leave data in an inconsistent state if an error occurs partway through. Always start with beginTransaction(), call commit() on success, and call rollBack() on failure.

In a catch block, it is safer to check inTransaction() before calling rollBack(). Calling rollBack() when no transaction is active will cause an error.

Transactions are also effective for bulk INSERT operations. In auto-commit mode, each row is committed individually, but wrapping the inserts in a transaction and committing once at the end significantly improves performance. Use new PDO() to connect to the database, and PDO::prepare() to execute SQL statements. For details on error handling, see try / catch.

If you find any errors or copyright issues, please .