When using MySQL, understanding how transactions work is essential. Transactions serve as a way to group multiple queries and ensure they are executed atomically, meaning either all or none of the queries succeed.
In MySQLi, a transaction is initiated by deactivating the autocommit mode using the autocommit(FALSE) statement. Autocommit is the default behavior of MySQL, which means every query is executed independently and immediately. By disabling autocommit, you enable transaction control, allowing you to group multiple queries and execute them as a single unit.
After grouping the desired queries within the transaction, you must explicitly end it. There are two ways to end a transaction:
Consider the following PHP code snippet:
<?php // Database connection $mysqli = new mysqli('localhost', 'username', 'password', 'database'); // Start transaction $mysqli->autocommit(FALSE); // Queries within the transaction $mysqli->query('UPDATE `table` SET `column` = 1'); $mysqli->query('UPDATE `table1` SET `column1` = 2'); // Commit or rollback if ($allQueriesExecutedSuccessfully) { $mysqli->commit(); } else { $mysqli->rollback(); } ?>
In this example, the autocommit mode is disabled using autocommit(FALSE), initiating a transaction. Multiple queries are executed within the transaction. Based on the execution status, the transaction is either committed or rolled back.
The above is the detailed content of How Do I Start and End Transactions in MySQLi?. For more information, please follow other related articles on the PHP Chinese website!