简体   繁体   English

从存储过程中遍历MySQL结果

[英]Looping through MySQL results from stored procedure

For the sake of simplicity here, I have the following SQL query: 为了简单起见,我有以下SQL查询:

"SELECT id,name FROM employees WHERE birthdate<'$dymd'"

If I want use records from standard (not stored procedure) query, the code looks like this: 如果我想使用标准(非存储过程)查询中的记录,则代码如下所示:

$sql="SELECT id,name FROM employees WHERE birthdate<'$dymd'";

$rst=$mysqli->query($sql);

while($row=$rst->fetch_assoc())
{
  ...
}

$rst->free();

But if I store my query into stored procedure: 但是如果我将查询存储到存储过程中:

CREATE PROCEDURE GetEmployees(IN dymd DATE)
  READS SQL DATA
BEGIN
  SELECT id,name FROM employees WHERE birthdate<dymd;
END;

I cannot use previous loop (I get the error message: "Commands out of sync; you can't run this command now"). 我无法使用上一个循环(我收到错误消息:“命令不同步;您现在不能运行此命令”)。 I have to loop like this: 我必须像这样循环:

$sql="CALL GetEmployees('$dymd')";

$rst=$mysqli->query($sql);

if($rst->num_rows)
{
  do
  {
    $row=$rst->fetch_assoc();
    ...
  }
  while($mysqli->next_result());
  $rst->free();
}

The question is why I need to explicitly push records pointer in case of records from stored procedure!? 问题是,为什么要从存储过程中获取记录,我需要显式推送记录指针! Why fetch_assoc() does not do it for me like in previous case? 为什么fetch_assoc()不像以前那样对我这样做?

Even more, the code above works only for one retrieved result set from stored procedure per PHP page. 甚至,以上代码仅适用于每个PHP页面从存储过程中检索到的一个结果集。 If I have two stored procedures (eg CALL YoungEmployees() and CALL OldEmployees()) on the same PHP page for the second stored procedure I get the already mentioned error message. 如果第二个存储过程在同一个PHP页面上有两个存储过程(例如CALL YoungEmployees()和CALL OldEmployees()),我会得到已经提到的错误消息。 If I use standard queries (not from stored procedures) then it works fine - both result sets are correctly presented on one page! 如果我使用标准查询(不是来自存储过程),则可以正常工作-两个结果集都正确显示在一页上!

According to @JurisGregov comment, the solution for this is; 根据@JurisGregov的评论,解决方案是:

//first stored procedure

$sql1="CALL YoungEmployees('$dymd')";

if($rst1=$mysqli->query($sql1))
{
  while($row1=$rst1->fetch_row())
  {
    ...
  }
  $rst1->close();
  $mysqli->next_result(); //!!!
}

//second stored procedure

$sql2="CALL OldEmployees('$dymd')";

if($rst2=$mysqli->query($sql2))
{
  while($row2=$rst2->fetch_row())
  {
    ...
  }
  $rst2->close();
  $mysqli->next_result(); //!!!
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM