首页 > 解决方案 > 缺少存储过程的第一个结果

问题描述

我执行存储过程的查询,其中有 3 个选择结果

select _id a;
select 2 a;
select 3 a; 

我有这样的mysqli来调用存储过程

$i = 0;
if ($server->connection->query("CALL sp_select(1)", MYSQLI_USE_RESULT)) {
    printf("res\n");
    do {
        $i++;
        printf("$i.do\n");
        if ($result = $server->connection->store_result()) {
            printf("$i.store\n");
            $data = $result->fetch_all(MYSQLI_ASSOC);
            $this->data[] = $data;
            $result->free_result();
            printf("$i.free\n");
        }
        if ($server->connection->more_results()) {
            printf("$i.more\n");
        }
    } while ($server->connection->next_result());
    echo json_encode($this->data);
}

该函数无法存储第一个结果。我只得到了第二和第三个结果。为什么我无法存储第一个结果?

标签: phpmysqlmysqli

解决方案


调用存储过程时mysqli_query(),函数本身会返回第一个结果。像这样的东西也应该收集第一个结果。

$result = $mysqli->query("CALL sp_select()");
$this->data[] = $result->fetch_all();
while ($mysqli->next_result()) {
    if ($result = $mysqli->store_result()) {
        $this->data[] = $result->fetch_all();
    }
}
echo json_encode($this->data);

看起来您混淆了query()whichmulti_query()不会返回初始结果。此代码将执行相同的操作:

$mysqli->multi_query("CALL sp_select()");
do {
    if ($result = $mysqli->store_result()) {
        $this->data[] = $result->fetch_all();
    }
} while ($mysqli->next_result());
echo json_encode($this->data);

推荐阅读