PHP: PDO transaction

这是一个关于如何在PHP中使用PDO对象的事务例子,所有操作要么都执行成功,要么不执行,在某些场景中必须要用到事务。

例子:

/**
 * Connect to MySQL and instantiate the PDO object.
 * Set the error mode to throw exceptions and disable emulated prepared statements.
 */$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '', array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_EMULATE_PREPARES => false
));

//We are going to assume that the user with ID #1 has paid 10.50.
$userId = 1;
$paymentAmount = 10.50;

//We will need to wrap our queries inside a TRY / CATCH block.
//That way, we can rollback the transaction if a query fails and a PDO exception occurs.
try{

    //We start our transaction.
    $pdo->beginTransaction();

    //Query 1: Attempt to insert the payment record into our database.
    $sql = "INSERT INTO payments (user_id, amount) VALUES (?, ?)";
    $stmt = $pdo->prepare($sql);
    $stmt->execute(array(
            $userId, 
            $paymentAmount,
        )
    );

    //Query 2: Attempt to update the user's profile.
    $sql = "UPDATE users SET credit = credit + ? WHERE id = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute(array(
            $paymentAmount, 
            $userId
        )
    );

    //We've got this far without an exception, so commit the changes.
    $pdo->commit();

} 
//Our catch block will handle any exceptions that are thrown.
catch(Exception $e){
    //An exception has occured, which means that one of our database queries
    //failed.
    //Print out the error message.
    echo $e->getMessage();
    //Rollback the transaction.
    $pdo->rollBack();
}

说明:
交易条款说明。
快速解释一些关键术语:

beginTransaction:启动事务,并且禁用MySQL的默认自动提交特性。例如:如果您运行一个INSERT查询,数据将不会被直接插入。
commit:当你提交一个事务时,你基本上是在告诉MySQL一切正常,你的查询结果是最终的。
rollBack:当您回滚一个事务时,您基本上是在告诉MySQL您不希望提交更改。这通常在查询失败时使用。

5.0
02
golang: 写文件
PHP 8新特性
嘻嘻

嘻嘻IT: 笔者是一个工作七八年的程序猿老鸟,从事涉及的技术栈主要包括PHP、Linux、Devops等,喜欢研究新技术,尝试新技术,提升技术自动化和开发效率,致力于write less,do more! 技术每年都会层出不穷,领域划分的越来越细,不可能学习所有的东西,保持对技术的好奇心,理解技术中核心思想,做一个有深度,有思想的开发!

Recent Posts

asciinema一款优秀终端会话录制工具(13.2k stars)

asciinema是一个优秀的…

21小时 ago

tldr pages一个linux命令帮助工具(48.5k stars)

tldr pages项目是一个…

21小时 ago

Odoo一款开源ERP和CRM系统(34.6k stars)

Odoo是一套基于网络的开源商…

22小时 ago

Seodity:提升SEO分析和内容创建

Seodity作为SEO分析的…

2天 ago

SocialBee一款AI社交媒体内容生成器

SocialBee的AI帖子生…

2天 ago

雪橇云VPN五一活动来了!全场15%的折扣!

雪橇云VPN一款是稳定全球多节…

2天 ago