使用MySQLi对象获取多个记录集

时间:2012-01-03 09:37:46

标签: mysqli recordset

我正在尝试使用如下存储过程返回多个记录集:

CREATE PROCEDURE `multiple`()
BEGIN    
    SELECT * FROM account;
    SELECT * FROM admin;    
END$$

当我在SQLYog之类的mysql UI中点击CALL multiple()时,我会在每个记录集的单独选项卡中得到结果。但是,当我尝试在我的PHP脚本中使用mysqli连接器调用此存储过程时,我只是得到第一个记录集。

这是我的php脚本:

<?php
// New Connection
$db = new mysqli('localhost','root','','db_test');

// Check for errors
if(mysqli_connect_errno()){
 echo mysqli_connect_error();
}
echo "<pre>";

// 1st Query
$result = $db->query("call multiple()");
if($result){
     // Cycle through results
    while ($row = $result->fetch_object()){
        $user_arr[] = $row;
    }
    // Free result set
    $result->close();
    $db->next_result();
}
print_r($user_arr);

我们如何使用mysqli对象获取第二个记录集?

1 个答案:

答案 0 :(得分:1)

你必须使用准备好的陈述:

创建程序:

DELIMITER $$
CREATE PROCEDURE `multiple`()
BEGIN    
    SELECT * FROM account;
    SELECT * FROM admin;    
END $$

在PHP中获取多个记录集:

//connection
$mysqli = new mysqli('hostname','username','password','db_name');

// Check for errors
if(mysqli_connect_errno()){
   echo mysqli_connect_error();
}

//prepare statement
$stmt = $mysqli->prepare("call multiple()");

//run statement
$stmt->execute();

//fetch all recorsets returned by procedure

$recordset_Counter = 0;

while ( $stmt->more_results() )
{
   echo "Recordset($recordset_Counter) : <br/>";
   $res = $stmt->get_result();

   //fetch all records from current recordset
   while( $row = $res->fetch_assoc() )
   {   print_r($row); echo "<br/>";  }

   $stmt->next_result();
   $recordset_Counter++;
}