php - 在 php/mysqli 中使用存储过程检索多个结果集

标签 php stored-procedures mysqli resultset

我有一个包含多个结果集的存储过程。我如何前进到 mysqli 中的第二个结果集以获得这些结果?

假设它是一个存储过程,例如:

create procedure multiples( param1 INT, param2 INT )
BEGIN

SELECT * FROM table1 WHERE id = param1;

SELECT * FROM table2 WHERE id = param2;

END $$

PHP 是这样的:

$stmt = mysqli_prepare($db, 'CALL multiples(?, ?)');

mysqli_stmt_bind_param( $stmt, 'ii', $param1, $param2 );

mysqli_stmt_execute( $stmt );

mysqli_stmt_bind_result( $stmt, $id );

那么这就是我无法开始工作的部分。我试过使用 mysqli_next_result 移动到下一个结果集,但无法让它工作。我们确实让它与 mysqli_store_result 和 mysqli_fetch_assoc/array/row 一起工作,但由于某种原因,所有的整数都作为空白字符串返回。

还有其他人遇到过这个问题并有解决方案吗?

最佳答案

我认为您在这里遗漏了一些东西。这是使用 mysqli 准备语句从存储过程中获取多个结果的方法:

$stmt = mysqli_prepare($db, 'CALL multiples(?, ?)');
mysqli_stmt_bind_param($stmt, 'ii', $param1, $param2);
mysqli_stmt_execute($stmt);
// fetch the first result set
$result1 = mysqli_stmt_get_result($stmt);
// you have to read the result set here 
while ($row = $result1->fetch_assoc()) {
    printf("%d\n", $row['id']);
}
// now we're at the end of our first result set.

//move to next result set
mysqli_stmt_next_result($stmt);
$result2 = mysqli_stmt_get_result($stmt);
// you have to read the result set here 
while ($row = $result2->fetch_assoc()) {
    printf("%d\n", $row['id']);
}
// now we're at the end of our second result set.

// close statement
mysqli_stmt_close($stmt);

使用 PDO你的代码看起来像:

$stmt = $db->prepare('CALL multiples(:param1, :param2)');
$stmt->execute(array(':param1' => $param1, ':param2' => $param2));
// read first result set
while ($row = $stmt->fetch()) {
    printf("%d\n", $row['id']);
}
$stmt->nextRowset();
// read second result set
while ($row = $stmt->fetch()) {
    printf("%d\n", $row['id']);
}

顺便问一下:你是故意使用程序风格的吗?在 mysqli 中使用面向对象的风格会让你的代码看起来更有吸引力(我个人的意见)。

关于php - 在 php/mysqli 中使用存储过程检索多个结果集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24985670/

相关文章:

php - 如何使用 MySQL 存储过程返回值数组?

PHP、MySQL - 结果数组洗牌会比 "select... order by rand()"更快吗?

php - 使用准备好的语句编写查询后对结果集进行分页,

php - mysqli_fetch_assoc()需要参数/调用成员函数bind_param()错误。如何获取并修复实际的mysql错误?

php - "or"的运算符优先级和赋值

php - 为什么 textarea 充满了神秘的空白?

c# - 来自存储过程的模式

sql-server - SQL IF ELSE 性能问题

php - 大型数据集的服务器缓存和客户端缓存之间的区别?

php - 在 prestashop 中拆分 Mailalerts 模块收件人