Home > Backend Development > PHP Problem > How to use PDO::beginTransaction correctly in PHP

How to use PDO::beginTransaction correctly in PHP

autoload
Release: 2023-03-09 12:20:01
Original
1748 people have browsed it

Transactions are a common operation in SQL. In daily operations, we often need to add, delete, and modify the database. Problems will inevitably occur when operating data. In order to avoid this kind of Big mistake, PHP provides beginTransaction function, this article will take you to take a look.

First, let’s take a look at the syntax of the beginTransaction() function:

beginTransaction (   )
Copy after login
  • Turn off the automatic submission mode. When the auto-commit mode is turned off, changes made to the database through the PDO object instance are not committed until PDO::commit() is called to end the transaction. Calling PDO::rollBack() will roll back changes made to the database and return the database connection to autocommit mode.

  • Return value: Return true on success, or false on failure.

Code example:

1. Database connection part:

<?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_CASE, PDO::CASE_UPPER);
    }
catch(PDOException $e)
{
    $pdo->rollBack();
    echo $e->getMessage();
}
?>
Copy after login

2. Open transaction:

    $pdo->beginTransaction();
/* 在全有或全无的基础上插入多行记录(要么全部插入,要么全部不插入) */
    $sql = "INSERT INTO fate (id, name, age)VALUES (10,&#39;王五&#39;,27)";
    $sth = $pdo->exec($sql);

/* 提交更改 */
$pdo->commit();
/* 现在数据库连接返回到自动提交模式 */
Copy after login

Recommended: 2021 PHP interview questions summary (collection)》《php video tutorial

The above is the detailed content of How to use PDO::beginTransaction correctly in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
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