Skip to content

事务处理

概述

PDO 事务确保一组 SQL 操作要么全部成功提交,要么全部失败回滚。beginTransaction() 开始事务,commit() 提交,rollBack() 回滚。事务是保证数据一致性的核心机制,在转账、订单处理等场景中不可或缺。

适用场景

  • 银行转账
  • 订单处理
  • 数据同步
  • 批量更新

基础概念

事务特性(ACID)

特性说明
Atomicity(原子性)所有操作要么全部成功,要么全部失败
Consistency(一致性)事务前后数据状态一致
Isolation(隔离性)并发事务互不影响
Durability(持久性)提交后数据永久保存

PDO 事务方法

方法功能
beginTransaction()开始事务
commit()提交事务
rollBack()回滚事务
inTransaction()检查是否在事务中

隔离级别

级别说明
READ UNCOMMITTED读未提交(最低)
READ COMMITTED读已提交
REPEATABLE READ可重复读(MySQL 默认)
SERIALIZABLE串行化(最高)

MySQL 默认隔离级别

MySQL/InnoDB 的默认事务隔离级别是 REPEATABLE READ

语法与代码示例

基本事务

php
<?php

declare(strict_types=1);

$pdo = new PDO('mysql:host=localhost;dbname=bank', 'root', '');

try {
    $pdo->beginTransaction();

    // 转账:从 Alice 扣 100,给 Bob 加 100
    $pdo->exec("UPDATE accounts SET balance = balance - 100 WHERE name = 'Alice'");
    $pdo->exec("UPDATE accounts SET balance = balance + 100 WHERE name = 'Bob'");
    $pdo->exec("INSERT INTO transactions (from_user, to_user, amount) VALUES ('Alice', 'Bob', 100)");

    $pdo->commit();
    echo "转账成功\n";
} catch (PDOException $e) {
    $pdo->rollBack();
    echo "转账失败: {$e->getMessage()}\n";
}

事务中的预处理语句

php
<?php

try {
    $pdo->beginTransaction();

    $stmt = $pdo->prepare('INSERT INTO orders (user_id, amount, status) VALUES (:uid, :amount, :status)');
    $stmt->execute(['uid' => 1, 'amount' => 99.9, 'status' => 'pending']);

    $orderId = $pdo->lastInsertId();

    $stmt = $pdo->prepare('INSERT INTO order_items (order_id, product_id, qty) VALUES (:oid, :pid, :qty)');
    $stmt->execute(['oid' => $orderId, 'pid' => 10, 'qty' => 2]);
    $stmt->execute(['oid' => $orderId, 'pid' => 20, 'qty' => 1]);

    $pdo->commit();
} catch (PDOException $e) {
    $pdo->rollBack();
    throw $e;
}

隔离级别设置

php
<?php

// 设置事务隔离级别
$pdo->exec("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED");

// 开始事务
$pdo->beginTransaction();
// ... 操作
$pdo->commit();

// MySQL 隔离级别
// READ UNCOMMITTED  - 脏读
// READ COMMITTED    - 不可重复读
// REPEATABLE READ   - 幻读(MySQL 默认)
// SERIALIZABLE       - 完全隔离

检查事务状态

php
<?php

if ($pdo->inTransaction()) {
    echo "当前在事务中\n";
} else {
    echo "不在事务中\n";
}

实战示例

事务管理器

php
<?php

declare(strict_types=1);

class TransactionManager
{
    public function __construct(private PDO $pdo) {}

    /**
     * 在事务中执行回调
     */
    public function transaction(callable $callback): mixed
    {
        $this->pdo->beginTransaction();

        try {
            $result = $callback($this->pdo);
            $this->pdo->commit();
            return $result;
        } catch (Throwable $e) {
            $this->pdo->rollBack();
            throw $e;
        }
    }
}

// 使用
$manager = new TransactionManager($pdo);

$result = $manager->transaction(function (PDO $pdo) {
    $pdo->exec("UPDATE accounts SET balance = balance - 100 WHERE id = 1");
    $pdo->exec("UPDATE accounts SET balance = balance + 100 WHERE id = 2");
    return true;
});

批量数据导入

php
<?php

declare(strict_types=1);

function importCsvInTransaction(PDO $pdo, string $filePath, int $batchSize = 500): array
{
    $results = ['imported' => 0, 'errors' => 0];

    $handle = fopen($filePath, 'r');
    if ($handle === false) {
        throw new RuntimeException("无法打开文件: {$filePath}");
    }

    $headers = fgetcsv($handle);
    $batch = [];
    $line = 0;

    while (($row = fgetcsv($handle)) !== false) {
        $line++;
        if ($row === [null]) continue;

        $data = array_combine($headers, $row);
        $batch[] = $data;

        if (count($batch) >= $batchSize) {
            $imported = importBatch($pdo, $batch);
            $results['imported'] += $imported['success'];
            $results['errors'] += $imported['failed'];
            $batch = [];
        }
    }

    // 处理剩余记录
    if (!empty($batch)) {
        $imported = importBatch($pdo, $batch);
        $results['imported'] += $imported['success'];
        $results['errors'] += $imported['failed'];
    }

    fclose($handle);
    return $results;
}

function importBatch(PDO $pdo, array $batch): array
{
    $pdo->beginTransaction();
    try {
        $stmt = $pdo->prepare('INSERT INTO products (name, price, sku) VALUES (:name, :price, :sku)');

        $success = 0;
        foreach ($batch as $item) {
            $stmt->execute([
                'name' => $item['name'],
                'price' => (float)$item['price'],
                'sku' => $item['sku'],
            ]);
            $success++;
        }

        $pdo->commit();
        return ['success' => $success, 'failed' => 0];
    } catch (PDOException $e) {
        $pdo->rollBack();
        return ['success' => 0, 'failed' => count($batch)];
    }
}

注意事项

嵌套事务限制

php
<?php

// PDO 不支持真正的嵌套事务
// 第二个 beginTransaction() 会抛出异常

// 解决方案:使用保存点(Savepoint)
function nestedTransaction(PDO $pdo, callable $callback): mixed
{
    if ($pdo->inTransaction()) {
        // 在已有事务中,使用保存点
        $savepoint = 'sp_' . bin2hex(random_bytes(4));
        $pdo->exec("SAVEPOINT {$savepoint}");
        try {
            $result = $callback($pdo);
            $pdo->exec("RELEASE SAVEPOINT {$savepoint}");
            return $result;
        } catch (Throwable $e) {
            $pdo->exec("ROLLBACK TO SAVEPOINT {$savepoint}");
            throw $e;
        }
    } else {
        $pdo->beginTransaction();
        try {
            $result = $callback($pdo);
            $pdo->commit();
            return $result;
        } catch (Throwable $e) {
            $pdo->rollBack();
            throw $e;
        }
    }
}

自动提交模式

php
<?php

// PDO 默认使用自动提交模式
// 每条 SQL 独立一个事务

// 开启事务后,自动提交暂停
$pdo->beginTransaction();
// 所有 SQL 在同一事务中
$pdo->commit();
// 恢复自动提交

最佳实践

1. 使用 try-finally 确保事务结束

php
<?php

$pdo->beginTransaction();
try {
    // ... 操作
    $pdo->commit();
} catch (Throwable $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    throw $e;
}

2. 事务保持简短

php
<?php

// 好:事务内只包含必须原子性的操作
$pdo->beginTransaction();
$pdo->exec("UPDATE accounts SET balance = balance - 100 WHERE id = 1");
$pdo->exec("UPDATE accounts SET balance = balance + 100 WHERE id = 2");
$pdo->commit();

// 不好:事务内包含耗时操作
$pdo->beginTransaction();
$pdo->exec("UPDATE ...");
sleep(30); // 不要在事务中等待
$pdo->exec("INSERT ...");
$pdo->commit();

进阶用法

调试与测试技巧

php
<?php
declare(strict_types=1);

// 单元测试辅助函数
function createTestResource(): mixed
{
    return match (true) {
        default => new stdClass(),
    };
}

// 调试输出函数
function debugOutput(mixed , string  = ''): void
{
     =  ? ": " : '';
     .= print_r(, true);
    fwrite(STDERR,  . "\n");
}

// 性能基准测试
function benchmark(callable , int  = 1000): float
{
     = hrtime(true);
    for ($i = 0; $i < $iterations; $i++) {
        $fn();
    }
    return (hrtime(true) - $start) / 1e9;
}

日志记录实践

php
<?php
declare(strict_types=1);

/**
 * 简易日志记录器
 */
class SimpleLogger
{
    private string $logFile;
    private string $level = 'INFO';

    public function __construct(string $logFile)
    {
        $this->logFile = $logFile;
    }

    public function info(string $message, array $context = []): void
    {
        $this->log('INFO', $message, $context);
    }

    public function warning(string $message, array $context = []): void
    {
        $this->log('WARNING', $message, $context);
    }

    public function error(string $message, array $context = []): void
    {
        $this->log('ERROR', $message, $context);
    }

    private function log(string $level, string $message, array $context): void
    {
        $timestamp = date('Y-m-d H:i:s');
        $contextStr = $context ? ' ' . json_encode($context, JSON_UNESCAPED_UNICODE) : '';
        $line = "[{$timestamp}] [{$level}] {$message}{$contextStr}\n";
        file_put_contents($this->logFile, $line, FILE_APPEND | LOCK_EX);
    }
}

配置与环境检测

php
<?php
declare(strict_types=1);

// 环境检测工具
class EnvironmentChecker
{
    public static function checkRequirements(array $requirements): array
    {
        $results = [];
        foreach ($requirements as $name => $check) {
            $results[$name] = is_callable($check) ? $check() : false;
        }
        return $results;
    }

    public static function getSystemInfo(): array
    {
        return [
            'php_version' => PHP_VERSION,
            'os' => PHP_OS,
            'sapi' => PHP_SAPI,
            'memory_limit' => ini_get('memory_limit'),
            'max_execution_time' => ini_get('max_execution_time'),
            'loaded_extensions' => get_loaded_extensions(),
        ];
    }
}

常见问题排查

问题可能原因解决方案
连接超时网络问题/配置错误检查配置,增加超时时间
权限不足文件/目录权限使用 chmod/chown 修正
性能下降索引缺失/数据量大添加索引,优化查询
数据不一致并发冲突/事务残留使用锁机制和事务
内存溢出大数据集/未释放资源增大内存限制,分批处理

故障排除步骤

  1. 检查错误日志和异常信息
  2. 确认配置和环境是否正确
  3. 使用调试工具逐步排查
  4. 参考官方文档查找已知问题

版本兼容性说明

功能最低版本说明
基础功能PHP 8.1本文档基准版本
只读属性PHP 8.1public readonly 修饰符
枚举类型PHP 8.1enum 类型和 match 表达式
FiberPHP 8.1协程/轻量级并发
命名参数PHP 8.0foo(arg_name: value)
联合类型PHP 8.0`int
Null 安全运算符PHP 8.0$obj?->method()
析构器 promotionPHP 8.0__construct(public $x)
php
<?php
declare(strict_types=1);

// 版本兼容性检测
function ensureVersion(string $minVersion): void
{
    if (version_compare(PHP_VERSION, $minVersion, '<')) {
        throw new RuntimeException(
            sprintf('需要 PHP %s+, 当前版本: %s', $minVersion, PHP_VERSION)
        );
    }
}

ensureVersion('8.1.0');

参考链接