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

How to use PDO::beginTransaction correctly in PHP

autoload
autoloadOriginal
2021-04-26 09:52:131694browse

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 (   )
  • 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();
}
?>

2. Open transaction:

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

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

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!

Statement:
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