Home > Backend Development > PHP Tutorial > In-depth analysis of PDO::commit() in PHP

In-depth analysis of PDO::commit() in PHP

autoload
Release: 2023-04-09 22:14:02
Original
4740 people have browsed it

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    (   )
Copy after login
  • 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,&#39;王五&#39;,27)";
    $sth = $pdo->exec($sql);
/* 提交更改 */
$pdo->commit();
/* 现在数据库连接返回到自动提交模式 */
}
catch(PDOException $e)
{
    $pdo->rollBack();
    echo $e->getMessage();
}
?>
Copy after login

2. Submit DLL transaction

<?php
/*  开始一个事务,关闭自动提交 */
$dbh->beginTransaction();

$sth = $dbh->exec("DROP TABLE fate");

/* 更改数据库架构 */
$dbh->commit();

/* 现在数据库连接返回到自动提交模式 */
?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template