【发布时间】:2020-01-23 06:31:53
【问题描述】:
我有一些 PHP 代码来执行多个查询,其中一个查询有错误。但是 PHP 没有检测到它。这是代码
$updateCategoriesQ = "DELETE FROM category_products WHERE product = $id; INSERT INTO category_products (category, products) VALUES ";
foreach ($product['categories'] as $key) {
$updateCategoriesQ .= "(".mysqli_real_escape_string($connect, $key)."', $id), "; //error is here in the quote
}
$updateCategoriesQ = rtrim($updateCategoriesQ, ', ');
o($updateCategoriesQ);
$updateCategories = mysqli_multi_query($connect, $updateCategoriesQ);
if($updateCategories){
o('query ok'); //receives this output (wrapper function for echo)
}
形成的查询是
DELETE FROM category_products WHERE product = 1; INSERT INTO category_products (category, products) VALUES (1', 1), (2', 1)
第二个查询有错误,但 PHP 说没问题。如果我在第一个查询(删除)中创建错误,那么它会抛出错误,但如果错误在第二个查询中则不会。这里有不同的捕获错误的方法吗?
【问题讨论】:
-
您是否启用并正确配置了错误报告?检查 phpinfo() 输出以验证您的配置。
-
mysqli_multi_query()只返回第一次查询成功。要获得第二个查询的结果,您必须调用mysqli_next_result()。 -
我建议不要使用
mysqli_multi_query()。收益甚微,这让事情变得更加复杂。 -
另外,您不能将准备好的语句与多查询一起使用。这比使用
mysqli_real_escape_string()更好。 -
@Barmar 我听到了你的建议,但你能分享一个例子吗?我一直没能找到它。我看到了如何使用它的结果,但没有看到如何检查查询是否成功。
标签: php mysqli error-handling mysqli-multi-query