mysqli 处理具有不同列的多个结果集的准备过程调用

mysqli handle prepared procedure call with multiple result sets with different columns

当结果集有不同的列时,是否有办法从一个准备好的查询中处理多个结果集?

我有这样的程序:

CREATE PROCEDURE usp_CountAndList (in_SomeValue int)
BEGIN
  SELECT COUNT(*) AS ListCount FROM Table WHERE SomeValue = in_SomeValue;

  SELECT
    Name, Cost, Text
  FROM Table WHERE SomeValue = in_SomeValue
  ORDER BY
    Name
  LIMIT 25;
END

我的 PHP 代码如下所示:

$some_value = $_POST["SomeValue"];

if($some_value != null) {
    $dbh = mysqli_connect(...connection stuff...) or die ('I cannot connect to the database.');

    $query = $dbh->prepare("CALL usp_CountAndList( ? );");
    $query->bind_param("i", $some_value);
    if($query->execute() == true) {
        $meta = $query->result_metadata();
        $fields = $meta->fetch_fields();
        var_dump($fields);

        $query->store_result();
        $query->bind_result($list_count);
        while($query->fetch()) {
            print_r("<TR>");
            print_r("<TD>" . $list_count ."</TD>");
            print_r("</TR>\n");
        }

        $query->free_result();
        $dbh->next_result();

        $meta = $query->result_metadata();
        $fields = $meta->fetch_fields();
        var_dump($fields);

        $query->store_result();
        $query->bind_result($name, $cost, $text);

        while($query->fetch()) {
            print_r("<TR>");
            print_r("<TD>" . $name . "</TD>");
            print_r("</TR>\n");
        }

        $query->free_result();
        $dbh->next_result();
    }
    else {
        print_r("Query failed: " . $query->error . "<BR>\n");
        exit(0);
    }

    $query->close();
    $dbh->close();
}

我 运行 遇到的问题是,看起来我正在为第二个结果集获取相同的元数据,即使它返回的是一组完全不同的列,这意味着我的第二个 bind_result 调用导致以下错误:

PHP Warning:  mysqli_stmt::bind_result() [<a href='mysqli-stmt.bind-result'>mysqli-stmt.bind-result</a>]: Number of bind variables doesn't match number of fields in prepared statement

我已经为此苦苦思索了一段时间,只是不清楚我做错了什么……这几乎像是一个 mysqli 错误。有没有人有一些示例代码来展示如何做我正在尝试的事情?

基本上有一些要求才能正常工作...

基本上在您的示例中,使用 $query->next_result() 而不是 $dbh->next_result()。

mysqli_stmt::next_result

我只发现了一个 其他人试图这样做。