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

Mac*_*ony 15 php mysqli stored-procedures resultset

我有一个具有多个结果集的存储过程.如何进入mysqli的第二个结果集来获得这些结果?

让我们说这是一个存储过程,如:

create procedure multiples( param1 INT, param2 INT )
BEGIN

SELECT * FROM table1 WHERE id = param1;

SELECT * FROM table2 WHERE id = param2;

END $$
Run Code Online (Sandbox Code Playgroud)

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 );
Run Code Online (Sandbox Code Playgroud)

然后这是我无法工作的部分.我已经尝试使用mysqli_next_result移动到下一个结果集,但无法使其工作.我们确实让它与mysqli_store_result和mysqli_fetch_assoc/array/row一起使用,但由于某种原因,所有的int都以空字符串形式返回.

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

Ste*_*rig 14

我想你在这里遗漏了一些东西(以下未经测试):

$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_use_result($db);
// 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.
mysqli_free_result($result1);

//move to next result set
mysqli_next_result($db);
$result2 = mysqli_use_result($db);
// 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.
mysqli_free_result($result2);

// close statement
mysqli_stmt_close($stmt);
Run Code Online (Sandbox Code Playgroud)

使用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']);
}
Run Code Online (Sandbox Code Playgroud)

但我听说MySQL PDO驱动程序PDOStatement::nextRowset()没有实现,因此无法检索多个结果集:

因此,根据您的PHP版本,您必须坚持使用您的mysqli-solution.顺便问一下:你是故意使用程序风格吗?使用面向对象的风格mysqli会使你的代码看起来更有吸引力(我的个人观点).