gpt4 book ai didi

PHP MySQL 事务捕获错误

转载 作者:行者123 更新时间:2023-11-29 05:08:46 24 4
gpt4 key购买 nike

我已经找了两天了,仍然没有找到答案。假设我有下面的 PHP 代码:

$mysqli->begin_transaction();
mysqli_query($mysqli, "DELETE FROM Test WHERE ID=1");
mysqli_query($mysqli, "DELETE FROM TEST WHEREE ID=2"); <-- THIS ONE WILL FAIL BECAUSE OF TYPO
mysqli_query($mysqli, "DELETE FROM Test WHERE ID=3");
if ($mysqli->commit()) {
//SUCCESS
}
else {
//Failed
$mysqli->rollback();
}

我无法检查事务中的查询是否全部成功,因为当我执行这些查询时,提交函数总是返回 true。

如何检查交易中的所有查询是否已成功?

最佳答案

常见的做法:

$mysqli->begin_transaction();
try {
mysqli_query($mysqli, "DELETE FROM Test WHERE ID=1");
mysqli_query($mysqli, "DELETE FROM TEST WHEREE ID=2"); <-- THIS ONE WILL FAIL BECAUSE OF TYPO
mysqli_query($mysqli, "DELETE FROM Test WHERE ID=3");
$mysqli->commit();
} catch (\Exception $e) {
// this will show statement with error
echo $e->getMessage();
$mysqli->rollback();
throw $e;
}

关于PHP MySQL 事务捕获错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43170943/

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