繁体   English   中英

调用mysqli_multi_query后如何获取所有错误?

[英]How to get all errors after calling to mysqli_multi_query?

我正在使用此代码:

$mysqli = new mysqli(...);

$sql = file_get_contents("my_sql_file.sql");
$result = $mysqli->multi_query($sql);

if (!$result)
  report_error(); //my function

while ($mysqli->more_results()) {
  $result = $mysqli->next_result();
  if (!$result)
    report_error();
}

但是,上面代码中的“ while”循环变成了无限循环。 哪里不对了?

实际上,您的代码没有任何意义。 处理多查询的正确方法如下(请参阅php手册

if ($mysqli->multi_query($query)) {
    do {
        // store first result set 
        if ($result = $mysqli->store_result()) {
            while ($row = $result->fetch_row()) {
                // do something with the row
            }
            $result->free();
        }
        else { error_report(); }
    } while ($mysqli->next_result());
}
else { error_report(); }

问题中提供的代码进入infitie循环,因为“如果第二个或后一个查询不返回结果,或者即使查询不是有效的SQL查询,more_results();在任何情况下都返回true。” php.net: http://us3.php.net/manual/en/mysqli.multi-query.php#104076

此外,由于未丢弃结果,mysqli_more_results始终在代码中返回true,因此每次调用mysqli_next_result后必须调用mysqli_store_results丢弃结果。 参见: http : //us3.php.net/manual/en/mysqli.multi-query.php#91677

当通过mysqli_multi_query执行MySQL文本(用分号分隔的多命令)时,没有官方的方法来捕获所有错误。 当函数mysqli_multi_query遇到错误的SQL命令时,它将停止执行,因此只能捕获第一个错误(无论错误发生在何处,在第一个SQL命令或SQL文本中的任何其他SQL命令中)。

与乔恩对此问题的回答有关: mysqli_multi_query何时停止执行?

并且如http://www.php.net/manual/en/mysqli.multi-query.php#106126中所述 ,可以通过扫描mysqli_next_result coz来捕获第一个错误:$ mysqli-> next_result()将返回false。用完语句,或者下一个语句有错误。

最后的答案是,使用mysqli_store_result调用mysqli_next_result后必须丢弃结果:

$mysqli = new mysqli(...);

$sql = file_get_contents("my_sql_file.sql");
$result = $mysqli->multi_query($sql);

if (!$result)
  report_error(); //my function

while ($mysqli->more_results()) {
  $result = $mysqli->next_result();

  //important to make mysqli_more_results false:
  $discard = $mysqli->store_result(); 

  if (!$result)
    report_error();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM