【问题标题】:Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 2014 Cannot execute queries while there are pending result sets致命错误:未捕获的 PDOException:SQLSTATE [HY000]:一般错误:2014 存在未决结果集时无法执行查询
【发布时间】:2021-08-10 06:29:34
【问题描述】:
$query = "CALL GetAllCategories()";
$stmt = $pdo->prepare($query);
$stmt->execute();
$categories = $stmt->fetchAll();

我使用此代码使用存储过程从数据库中获取类别,没有问题,一切正常。

这是 GetAllCategories() 程序:

DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetAllCategories`()
BEGIN
    SELECT
        id, name
    FROM
        categories ;
END$$
DELIMITER ;

之后,我使用常规的 SQL 语句来获取帖子(为了测试,我将使用存储过程)

这是获取帖子的查询:

SELECT
    `p`.`id`,
    `u`.`name` AS `author`,
    `post_title`,
    `post_date`,
    `post_img`,
    `post_content`
FROM
    `posts` `p`
JOIN `users` `u` ON
    `p`.`author_id` = `u`.`id`;

从这里问题发生了?????????

error image

出现此错误:

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 2014 Cannot execute queries while there are pending result sets. Consider unsetting the previous PDOStatement or calling PDOStatement::closeCursor() in C:\xampp\htdocs\cms\index.php:17 Stack trace: #0 C:\xampp\htdocs\cms\index.php(17): PDO->prepare('SELECT\n `p`....') #1 {main} thrown in C:\xampp\htdocs\cms\index.php on line 17

尝试多次尝试时,我将GetAllCategories() 存储过程更改为常规查询语句:

$query = "SELECT * FROM `categories`";

问题消失了?????????

谁能解释一下为什么存储过程会出现这种情况?

最后一件事,在这个issue之后,从PHPMyAdmin浏览posts表时又出现了一个问题

posts table browsing error

【问题讨论】:

  • 如果您使用fetchAll(),则不会发生这种情况,因为这通常是修复此问题的方法。
  • fetchAll()之后尝试$stmt->closeCursor();
  • 所以可能是因为您尝试将过程与常规一起使用,所以您应该使用一种类型的所有查询。

标签: php mysql database stored-procedures pdo


【解决方案1】:

我在从GetAllCategories()存储过程中获取数据后使用$stmt->closeCursor();来解决这个错误。

$query = "CALL GetAllCategories()";
$stmt = $pdo->prepare($query);
$stmt->execute();
$categories = $stmt->fetchAll();
$stmt->closeCursor();

【讨论】:

    【解决方案2】:

    Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 2014 Cannot execute queries while there are pending result sets. Consider unsetting the previous PDOStatement

    此错误总是在同时执行两次时发生,例如:

    1. 案例 1

      if(!$query->execute())

      die("SQL FAILED");
      

      其他

      $query->execute(); // **DELETE THIS ONE**
      

    解决方法:不需要第二次执行,去掉第二次,第一次执行已经执行了。

    1. 如果第一种情况不起作用,请在 $query=$handler->prepare($sql);

      之后使用此解决方案调用此函数

      $query->closeCursor();

    我希望这个解决方案有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-13
      • 2018-11-18
      • 2015-06-12
      • 2017-07-21
      • 1970-01-01
      • 2017-09-26
      • 1970-01-01
      • 2019-12-17
      相关资源
      最近更新 更多