php - 我如何确保我捕捉到来自 MySQLi::multi_query 的所有错误?

标签 php mysql mysqli error-handling

docs for multi_query说:

Returns FALSE if the first statement failed. To retrieve subsequent errors from other statements you have to call mysqli_next_result() first.

docs for next_result说:

Returns TRUE on success or FALSE on failure.

最后,multi_query 文档中发布的示例使用 next_result 的返回值来确定何时不再有查询;例如停止循环:

<?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 语法中有错误。

如何检查所有查询是否有错误?

最佳答案

尽管文档中有代码示例,但更好的方法可能是这样的:

if ($mysqli->multi_query(...)) {
  do {
    // fetch results

    if (!$mysqli->more_results()) {
      break;
    }
    if (!$mysqli->next_result()) {
      // report error
      break;
    }
  } while (true);
}

关于php - 我如何确保我捕捉到来自 MySQLi::multi_query 的所有错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43847851/

相关文章:

PHP MySQL 查询不工作

mysql - 使用 GROUP BY 和 SUM LEFT JOIN 3 个表

php - 当多个用户在短时间内完成堆叠查询时,是否有可能在彼此之间潜入?

php mysqli stmt num_rows 总是返回 0

php - 由于某人输入数据的方式很奇怪,无法生成准确的结果 (1 12 13)

php - 修改MYSQL字段中的一个值有多个值(复杂)

php - 检索数据库记录以在 PHP 代码中使用

mysql - 我正在尝试创建一个查询以将数据从一个表带到另一个表,如下所述?

php - 列计数与第 1 行的值计数不匹配 - 检查 MySQL 中的某些列是否唯一

php - 变量在 symfony2 中不存在