doufangzhang4454 2017-08-01 07:58
浏览 111
已采纳

在PHP中,当我使用PDO调用MySQL存储过程,然后另一个查询时,我收到一个错误:[重复]

This question already has an answer here:

In PHP, when I call a MySQL stored procedure using PDO, and then another PDO query, just like this:

$dbh = new PDO('mysql:host=localhost;dbname=db1','user1','password1');

$query = "CALL get_token()";
$stmt = $dbh->query($query);
$array = $stmt->fetchAll();

$query = "SELECT * FROM `table1`";
$stmt = $dbh->query($query);
$array = $stmt->fetchAll();

The MySQL stored procedure is about like this:

CREATE PROCEDURE `get_token`()
BEGIN
    DECLARE token CHAR(64);
    DECLARE expire SMALLINT;

    SELECT `token`, `expire` INTO token, expire FROM `token`;

    SELECT token, expire;
END$$

And I got the following error message (using try...catch to catch it):

General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.

Even if I followed the instructions described in the above error message (that means using fetchAll() and setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute), I still got the same error message.

If I change the first query to a normal SELECT SQL query, instead of a stored procedure, I won't get this error. So it seems that the problem arises from the stored procedure.

But how can I fix this?

</div>
  • 写回答

2条回答 默认 最新

  • dtmu88600 2017-08-01 08:18
    关注

    That's because you are not freeing the cursor of the first query. It still waits for another fetchAll. From http://php.net/manual/en/pdo.query.php

    If you do not fetch all of the data in a result set before issuing your next call to PDO::query(), your call may fail. Call PDOStatement::closeCursor() to release the database resources associated with the PDOStatement object before issuing your next call to PDO::query().

    So $stmt->closeCursor(); after first $array = $stmt->fetchAll(); should be sufficient.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行