Documentation Home
Connectors and APIs Manual
Download this Manual

Connectors and APIs Manual  /  ...  /  API support for transactions API support for transactions

Copyright 1997-2020 the PHP Documentation Group.

The MySQL server supports transactions depending on the storage engine used. Since MySQL 5.5, the default storage engine is InnoDB. InnoDB has full ACID transaction support.

Transactions can either be controlled using SQL or API calls. It is recommended to use API calls for enabling and disabling the auto commit mode and for committing and rolling back transactions.

Example 7.35 Setting auto commit mode with SQL and through the API

$mysqli = new mysqli("", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
/* Recommended: using API to control transactional settings */
/* Won't be monitored and recognized by the replication and the load balancing plugin */
if (!$mysqli->query('SET AUTOCOMMIT = 0')) {
    echo "Query failed: (" . $mysqli->errno . ") " . $mysqli->error;

Optional feature packages, such as the replication and load balancing plugin, can easily monitor API calls. The replication plugin offers transaction aware load balancing, if transactions are controlled with API calls. Transaction aware load balancing is not available if SQL statements are used for setting auto commit mode, committing or rolling back a transaction.

Example 7.36 Commit and rollback

$mysqli = new mysqli("", "user", "password", "database");
$mysqli->query("INSERT INTO test(id) VALUES (1)");
$mysqli->query("INSERT INTO test(id) VALUES (2)");

Please note, that the MySQL server cannot roll back all statements. Some statements cause an implicit commit.

See also