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

mysqli::savepoint

(mysqli_savepoint) Set the named transaction save point
Name:mysqli::savepoint
Category:MySQLi
Programming Language:php
One-line Description:Methods to create a savepoint in a transaction

mysqli::savepoint() is a method used to create a savepoint in a transaction. A savepoint is a tag in a transaction that can be rolled back to the state where the tag is located at any time during the transaction.

Usage: mysqli::savepoint(string $savepoint_name) : bool

parameter:

  • $savepoint_name: The name of the savepoint must be a string.

Return value:

  • Returns true on success, and false on failure.

Example:

 // 创建数据库连接$mysqli = new mysqli("localhost", "username", "password", "database"); // 检查连接是否成功if ($mysqli->connect_errno) { echo "连接数据库失败: " . $mysqli->connect_error; exit(); } // 开始事务$mysqli->begin_transaction(); // 执行一些数据库操作$mysqli->query("INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com')"); $mysqli->query("UPDATE accounts SET balance = balance - 100 WHERE user_id = 1"); // 创建保存点if ($mysqli->savepoint("my_savepoint")) { echo "保存点创建成功!"; // 执行更多数据库操作$mysqli->query("DELETE FROM orders WHERE user_id = 1"); $mysqli->query("UPDATE accounts SET balance = balance + 100 WHERE user_id = 2"); // 回滚到保存点if ($mysqli->rollback_to("my_savepoint")) { echo "回滚成功!"; } else { echo "回滚失败!"; } } else { echo "保存点创建失败!"; } // 提交事务$mysqli->commit(); // 关闭数据库连接$mysqli->close();

In the example above, we first create a database connection and then start a transaction. In a transaction, we performed some database operations and created a savepoint using savepoint() method. Next, we continued to perform some other database operations and rolled the transaction back to the state where the savepoint was located using rollback_to() method. Finally, we committed the transaction and closed the database connection.

Note that savepoint() and rollback_to() methods are only available in transaction-enabled storage engines, such as InnoDB. These methods will fail if you are using a storage engine that does not support transactions.

Similar Functions
Popular Articles