Current Location: Home> Function Categories> mysqli::begin_transaction

mysqli::begin_transaction

(mysqli_begin_transaction) Start a transaction
Name:mysqli::begin_transaction
Category:MySQLi
Programming Language:php
One-line Description:Start a transaction on a MySQL database

Function name: mysqli::begin_transaction()

Applicable version: PHP 5 >= 5.5.0, PHP 7

Function Description: This function is used to start a transaction on a MySQL database.

Usage: mysqli::begin_transaction(int $flags = 0, string $name = NULL) : bool

parameter:

  • $flags: Optional parameter to specify the behavior of the transaction. The default is 0, which means the default behavior is used. You can set it with the following constants:

    • MYSQLI_TRANS_START_READ_ONLY: Start read-only transaction
    • MYSQLI_TRANS_START_READ_WRITE: Start read and write transactions
    • MYSQLI_TRANS_START_WITH_CONSISTENT_SNAPSHOT: Start a consistent snapshot transaction
  • $name: Optional parameter to specify the name of the transaction. This parameter can be used if you use the InnoDB engine and support named transactions.

Return value:

  • Return true if the transaction starts successfully; otherwise return false.

Example:

 // 创建数据库连接$mysqli = new mysqli("localhost", "username", "password", "database"); // 检查连接是否成功if ($mysqli->connect_errno) { die("连接数据库失败:" . $mysqli->connect_error); } // 启动读写事务if ($mysqli->begin_transaction(MYSQLI_TRANS_START_READ_WRITE)) { try { // 执行事务操作$mysqli->query("INSERT INTO users (name, email) VALUES ('John', 'john@example.com')"); $mysqli->query("UPDATE users SET email = 'new_email@example.com' WHERE id = 1"); // 提交事务$mysqli->commit(); echo "事务已提交"; } catch (Exception $e) { // 回滚事务$mysqli->rollback(); echo "事务已回滚:" . $e->getMessage(); } } else { echo "无法启动事务"; } // 关闭数据库连接$mysqli->close();

The above example demonstrates how to start a read and write transaction using the mysqli::begin_transaction() function and perform insert and update operations in the transaction. If the transaction executes successfully, the transaction is committed; if an exception occurs, the transaction is rolled back. Note When using transactions, you must ensure that the database engine supports transaction operations, such as the InnoDB engine.

Similar Functions
Popular Articles