gpt4 book ai didi

php - 我必须在 exit() 之前 rollBack() 吗?

转载 作者:行者123 更新时间:2023-12-03 02:40:33 25 4
gpt4 key购买 nike

我有这样的代码

try {
$pdo->beginTransaction();
$stmt = $pdo->prepare($query1);
$stmt->execute($x);
} catch (Exception $e) {
$pdo->rollBack();
throw->$e;
}

if (condition) {
exit();
}

$x['column1'] = 'string1';
$x['column2'] = 'string2';
$x['column3'] = 'string3';

try {
$stmt = $pdo->prepare($query2);
$stmt->execute($x);
$pdo->commit();
} catch (Exception $e) {
$pdo->rollBack();
throw->$e;
}

如果if条件成功并且代码执行了exit()

$pdo相关的所有内容也都是安全的还是我在exit()之前添加$pdo->rollBack();?

最佳答案

从技术上讲,你不需要。

PHP 将在退出时关闭数据库连接。
数据库将在关闭时回滚所有事件事务。

但是,这种情况不太可能在您的代码中发生,因为现在它是错误的。您必须将整个事务包装在 try catch 中,而不仅仅是数据库操作。否则,如果在“条件”部分抛出异常,它将破坏事务但不会被捕获。

此外,使用退出本身就是一种不好的做法,而且在事务中更是不好的做法。

但是如果你真的需要它(实际上你不需要),那么就做类似的事情

try {
$pdo->beginTransaction();
$stmt = $pdo->prepare($query1);
$stmt->execute($x);

if (condition) {
throw new Exception("Stopped on condition");
}

$x['column1'] = 'string1';
$x['column2'] = 'string2';
$x['column3'] = 'string3';

$stmt = $pdo->prepare($query2);
$stmt->execute($x);
$pdo->commit();
} catch (Throwable $e) {
$pdo->rollBack();
throw->$e;
}

关于php - 我必须在 exit() 之前 rollBack() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61365209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com