How to Turns on or off auto-committing database modifications in PHP ?


In PHP, auto-committing database modifications can be turned on or off using the autocommit() method of the mysqli class.

To turn on auto-commit, use the following code:

$mysqli = new mysqli("localhost", "username", "password", "database");
$mysqli->autocommit(TRUE);

To turn off auto-commit, use the following code:

$mysqli = new mysqli("localhost", "username", "password", "database");
$mysqli->autocommit(FALSE);

Once auto-commit is turned off, you can manually commit or rollback transactions using the commit() and rollback() methods of the mysqli class.

Here's an example of how to use transactions with auto-commit turned off:

$mysqli = new mysqli("localhost", "username", "password", "database");
$mysqli->autocommit(FALSE);

// Start a transaction
$mysqli->begin_transaction();

// Perform some database operations
$mysqli->query("INSERT INTO users (name, email) VALUES ('John Doe', '[email protected]')");
$mysqli->query("UPDATE accounts SET balance = balance - 100 WHERE user_id = 1");

// Commit the transaction
$mysqli->commit();

If any of the database operations fail, you can rollback the transaction using the rollback() method:

$mysqli = new mysqli("localhost", "username", "password", "database");
$mysqli->autocommit(FALSE);

// Start a transaction
$mysqli->begin_transaction();

// Perform some database operations
$mysqli->query("INSERT INTO users (name, email) VALUES ('John Doe', '[email protected]')");
$mysqli->query("UPDATE accounts SET balance = balance - 100 WHERE user_id = 1");

// Rollback the transaction if any of the operations fail
if ($mysqli->errno) {
    $mysqli->rollback();
} else {
    $mysqli->commit();
}


About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.