search
HomeBackend DevelopmentPHP TutorialTransaction processing in PDO

Transaction is a very important function in operating the database. It allows you to schedule one or a series of SQL statements and then execute them together. During the execution process, if one of them fails to execute, it can be rolled back. All changed operations. If executed successfully, this series of operations will be permanently effective. Transactions can well solve the problem of out-of-synchronization when operating the database. At the same time, when executing large amounts of data through transactions, the execution efficiency can be improved Improved a lot.

The function of transaction processing can also be realized in PDO

1: Open the transaction: beginTransaction() method

beginTransaction() method will turn off the autocommit mode until the transaction is submitted Or restore after rolling back

2: Submit things: commit() method

commit() method completes the submission operation of things, and returns true if successful, otherwise returns false.

3: Rollback of things: rollBack() method

rollBack() method performs rollback operation of things.

For example:

$dbms='mysql';//数据库类型
$dbName='admin';//使用的数据库
$user='root';//数据库连接用户名
$pwd='password';//数据库连接密码
$host='localhost';//数据库主机名
$dsn="$dbms:host=$host;port=3306;dbname=$dbName";
try {
    $pdo = new PDO($dsn, $user, $pwd);//初始化一个PDO对象,就是创建了数据库连接对象$pdo
    $pdo->beginTransaction();//开启事物
    $query = "insert into user (username,password) values('admin','123456')";//需要执行的sql语句
    $res = $pdo->prepare($query);
    if ($res->execute()) {
        echo "数据添加成功";
    }else{
        echo "数据添加失败";
    }
    $pdo->commit();//执行事物的提交操作
}catch(PDOException $e){
    die("Error!: ".$e->getMessage().'<br>');
    $pdo->rollBack();//执行事物的回滚操作
}

Supplement:

Database Transaction refers to a series of operations performed as a single logical unit of work, either completely executed or not executed at all .
 Transaction processing ensures that data-oriented resources are not permanently updated unless all operations within the transactional unit complete successfully. By combining a set of related operations into a unit that either all succeeds or all fails, you can simplify error recovery and make your application more reliable. For a logical unit of work to become a transaction, it must satisfy the so-called ACID (Atomicity, Consistency, Isolation, and Durability) properties.
 A transaction is a logical unit of work in database operation, and the transaction management subsystem in the DBMS is responsible for transaction processing.
 Related properties:
 Atomic (Atomicity)
 Transactions must be atomic units of work; for their data modifications, either all of them are executed or none of them are executed. Typically, operations associated with a transaction have a common goal and are interdependent. If the system only performs a subset of these operations, it may defeat the overall purpose of the transaction. Atomicity eliminates the possibility for the system to process a subset of operations.
  Consistency (Consistency)
  When a transaction is completed, all data must be kept consistent. In the relevant database, all rules must be applied to transaction modifications to maintain the integrity of all data. At the end of the transaction, all internal data structures (such as B-tree indexes or doubly linked lists) must be correct. Some responsibility for maintaining consistency rests with the application developer, who must ensure that the application has enforced all known integrity constraints. For example, when developing an application for transferring money, you should avoid arbitrarily moving the decimal point during the transfer process.
 Isolation (Isolation)
 Modifications made by concurrent transactions must be isolated from modifications made by any other concurrent transactions. The state of the data when a transaction views the data is either the state before it was modified by another concurrent transaction, or the state after another transaction modified it. The transaction will not view the data in the intermediate state. This is called isolation because it enables the starting data to be reloaded and a series of transactions to be replayed so that the data ends up in the same state as the original transaction execution. The highest isolation level is achieved when a transaction is serializable. At this level, the results obtained from a set of transactions that can be executed in parallel are the same as those obtained by running each transaction serially. Because high isolation limits the number of transactions that can be executed in parallel, some applications lower the isolation level in exchange for greater throughput.
 Persistence (Duration)
 After a transaction is completed, its impact on the system is permanent. This modification will persist even in the event of a fatal system failure.


The above introduces the transaction processing in PDO, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.