PHP PDO Transactions: beginTransaction, Commit, Rollback
See how PHP PDO transactions use beginTransaction, commit, and rollback to keep related database changes consistent.

Contents

Begin Transaction
Begin Transaction is used to roll back the latest changes if an error occurs during bulk operations. In PHP, to provide convenience and transaction safety, this function starts a transaction before database operations and continues it until all operations complete successfully. When used in detail, this function is extremely useful for ensuring the security and consistency of database operations.
With the function call, “begin transaction” starts a transaction for the database operation. In this way, the transaction must be performed before it starts processing all database queries. After this transaction is started, it will continue until it is terminated with “commit” or “rollback” operations.
The “begin transaction function” used to start the transaction opens a database connection to execute queries and uses this connection throughout the transaction. After the transaction completes successfully, the connection is closed and becomes available for other queries.
Another important aspect of the “Begin transaction” function is ensuring the consistency of database operations. When the transaction starts, all changes are saved before processing all queries in the database. This prevents data corruption in case of any error or interruption. If the transaction fails, all changes are rolled back and the database is restored to its previous state.
The “Begin transaction” function allows a series of queries to be processed as a single transaction. This is extremely useful when multiple queries depend on each other. For example, during order processing, stock levels may need to be updated. Managing the dependencies between these operations can be easily done using the “begin transaction” function.
In conclusion, the “begin transaction” function is an extremely useful tool for ensuring the security and consistency of database operations in PHP. It can be used to handle operations as a single transaction, manage dependencies, and minimize the effects of errors. This function is a critical tool for database operations and an important topic every PHP developer should know. In addition, the “begin transaction” function can also improve the performance of database operations, because processing a series of queries as a single transaction can reduce the cost of opening and closing a connection per operation.
However, correct use of the “begin transaction” function is extremely important. After the transaction starts, it must be terminated with “commit” or “rollback” operations. The “Commit” operation saves all changes in the database and completes the transaction. The “Rollback” operation, on the other hand, rolls back all changes and cancels the transaction. Correct use of these operations is critical for ensuring the consistency of database operations.
To give another example, the “begin transaction” function can also prevent data integrity problems between multiple users or transactions. For example, if two users update the same record at the same time, data integrity problems can arise if the database operation is not performed correctly. The “Begin transaction” function can be used to prevent such problems.
In conclusion, the “begin transaction” function is extremely important for ensuring the consistency and security of database operations in PHP. It can be used to handle operations as a single transaction, manage dependencies, and minimize the effects of errors. However, correct use is extremely important, and it must be terminated with “commit” or “rollback” operations.
Now let’s try to understand these in more detail with begin transaction code examples.
Example 1:
We gave a different example for begin transaction in previous lessons. Now let’s reinforce it with another example. Suppose you created a form page. Imagine that this form page writes the data you receive from the user to 3 different tables in the database. Everything is great so far, but if an error occurs during the record operation in one of the tables while the data is being written, then things get a bit problematic. Because the data in the other 2 tables that the user has written will need to be deleted as a result of the error. Instead of restoring these rows one by one with database queries and increasing the processing load, we can get rid of the whole burden by using begin transaction.
By examining the example below, you can actually understand more clearly what I mean.
<?php
/* Auto-commit mode is disabled on this line together with the beginTransaction command, and a bulk transaction starts for the operations. */
$transaction->beginTransaction();
/* Let's perform a simple database operation and change the schema and data. */
$sth = $transaction->exec("DROP TABLE meyveler");
$sth = $transaction->exec("UPDATE içecekler SET name = 'muz'");
/* We notice the update above and roll back the transactions. */
$transaction->rollBack();
/* After rollBack runs, the database connection will return to auto-commit mode again. */
?>
Example 2: Registering a new user
In the following example, we use the “begin transaction” function to register a new user in the “users” table. When the transaction completes successfully, we save all changes with the “commit” operation. However, when an error occurs, we roll back all changes with the “rollback” operation.
<?php
try {
$conn = new PDO("mysql:host=localhost;dbname=myDB", "username", "password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->beginTransaction();
$sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'john.doe@example.com')";
$conn->exec($sql);
$conn->commit();
echo "New user added successfully";
} catch(PDOException $e) {
$conn->rollback();
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
Example 3: Updating a user’s information
In the following example, we update a user’s information in the “users” table. When the transaction completes successfully, we save all the changes with the “commit” operation. But if an error occurs, we roll back all the changes with the “rollback” operation.
<?php
try {
$conn = new PDO("mysql:host=localhost;dbname=myDB", "username", "password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->beginTransaction();
$sql = "UPDATE users SET email='jane.doe@example.com' WHERE id=1";
$conn->exec($sql);
$conn->commit();
echo "User information updated successfully";
} catch(PDOException $e) {
$conn->rollback();
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
Example 3: Processing multiple queries in a transaction
In the following example, we use the “begin transaction” function to process multiple queries. When the transaction completes successfully, we save all the changes with the “commit” operation. But if an error occurs, we roll back all the changes with the “rollback” operation.
<?php
try {
// Create the PDO object to connect to the database
$conn = new PDO("mysql:host=localhost;dbname=myDB", "username", "password");
// Set the error mode of the PDO object
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Start a new transaction
$conn->beginTransaction();
// Prepare the first query
$sql1 = "INSERT INTO users (name, email) VALUES (:name, :email)";
$stmt1 = $conn->prepare($sql1);
// Bind the parameters
$stmt1->bindParam(':name', $name);
$stmt1->bindParam(':email', $email);
// Assign the parameter values
$name = "John Doe";
$email = "john.doe@example.com";
// Execute the query
$stmt1->execute();
// Get the user's ID
$user_id = $conn->lastInsertId();
// Prepare the second query
$sql2 = "INSERT INTO orders (user_id, product_name, quantity) VALUES (:user_id, :product_name, :quantity)";
$stmt2 = $conn->prepare($sql2);
// Bind the parameters
$stmt2->bindParam(':user_id', $user_id);
$stmt2->bindParam(':product_name', $product_name);
$stmt2->bindParam(':quantity', $quantity);
// Assign the parameter values
$product_name = "Example Product";
$quantity = 1;
// Execute the query
$stmt2->execute();
// Complete the transaction
$conn->commit();
echo "New user and order added successfully";
} catch(PDOException $e) {
// Roll back the transaction if an error occurs
$conn->rollback();
echo "Error: " . $e->getMessage();
}
// Close the database connection
$conn = null;
?>
In this example, we first connect to the database with the PDO object. Then we start a new transaction using the “beginTransaction” function. In the first query, we insert a new user, and then we get the user’s ID using the “lastInsertId” function. Next, in the second query, we insert an order for this user. When the transaction completes successfully, we save all the changes with the “commit” operation. But if an error occurs, we roll back all the changes with the “rollback” operation.
PDO::beginTransaction
Begin transaction turns off autocommit mode. When this mode is off, PDO won’t make any changes to the database until the last change made in the database is made permanent with PDO::Commit().
Available since (PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0). PDO::beginTransaction — Prioritizes a batch operation and makes it possible to roll it back. To understand the topic better, you can also review the examples on PHP’s official website. Also, in our PHP lessons;
- PHP MySQL TRANSACTION Usage
- What Is Transaction Commit and How Is It Used?
- What Is rollBack and How Is It Used?
Also check out these topics!
Share it if it helped


