Transactions are a common operation in SQL
. PHP
also needs to connect to the database, so it needs to be compatible with some operations of SQL
. In PDO Among the
connection methods, PHP
provides the use of the commit()
function. This article will take you to take a look.
First let’s take a look at the syntax of the commit()
function in PDO
commit ( )
Return value: on success Return true, or return false on failure
Code example:
1. Submit a basic transaction
<?php $servername = "localhost"; $username = "root"; $password = "root123456"; $dbname = "my_database"; try { $pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); echo "连接成功"."<br>"; // $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->setAttribute(PDO::ATTR_CASE, PDO::CASE_UPPER); $pdo->beginTransaction(); /* 在全有或全无的基础上插入多行记录(要么全部插入,要么全部不插入) */ $sql = "INSERT INTO fate (id, name, age)VALUES (10,'王五',27)"; $sth = $pdo->exec($sql); /* 提交更改 */ $pdo->commit(); /* 现在数据库连接返回到自动提交模式 */ } catch(PDOException $e) { $pdo->rollBack(); echo $e->getMessage(); } ?>
2. Submit DLL transaction
<?php /* 开始一个事务,关闭自动提交 */ $dbh->beginTransaction(); $sth = $dbh->exec("DROP TABLE fate"); /* 更改数据库架构 */ $dbh->commit(); /* 现在数据库连接返回到自动提交模式 */ ?>
Recommendation:《2021 PHP Summary of interview questions (collection)》《php video tutorial》
The above is the detailed content of In-depth analysis of PDO::commit() in PHP. For more information, please follow other related articles on the PHP Chinese website!