如何确保我从MySQLi :: multi_query捕获了所有错误? [英] How do I ensure I caught all errors from MySQLi::multi_query?
问题描述
multi_query
的文档说:>
如果第一条语句失败,则返回FALSE.要从其他语句检索后续错误,必须首先调用mysqli_next_result().
Returns FALSE if the first statement failed. To retrieve subsequent errors from other statements you have to call mysqli_next_result() first.
next_result
的文档说:>
成功返回TRUE,失败返回FALSE.
Returns TRUE on success or FALSE on failure.
最后,文档中发布的multi_query
示例使用next_result
的返回值来确定何时不再有查询.例如停止循环:
Finally, the example posted in the docs for multi_query
use the return value from next_result
to determine when there are no more queries; e.g. to stop looping:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result()); // <-- HERE!
}
/* close connection */
$mysqli->close();
?>
我不知道提供的查询数量,也不知道将要执行的SQL.因此,我不能仅将查询数量与返回结果数量进行比较.但是,如果第三个查询是损坏的查询,那么我想向用户显示错误消息.但是我似乎没有办法判断next_result
是否失败,因为没有更多的查询要执行,还是因为SQL语法错误.
I don't know the number of queries provided, nor do I know anything about the SQL that I'm going to execute. I therefore can't just compare the number of queries against the number of returned results. Yet I want to display an error message to the user if, say, the third query was the broken query. But I don't seem to have a way to tell if next_result
failed because there were no more queries to execute, or if it's because there was an error in the SQL syntax.
如何检查所有查询中的错误?
How can I check all the queries for errors?
推荐答案
尽管有文档中的代码示例,也许更好的方法可能是这样的:
Despite the code example in the docs, perhaps the better method would be something like this:
if ($mysqli->multi_query(...)) {
do {
// fetch results
if (!$mysqli->more_results()) {
break;
}
if (!$mysqli->next_result()) {
// report error
break;
}
} while (true);
}
这篇关于如何确保我从MySQLi :: multi_query捕获了所有错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!