Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 2014 Cannot execute queries while there are pending result sets

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 2014 Cannot execute queries while there are pending result sets

$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() 存储过程更改为 reqular 查询语句:

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

问题消失

谁能解释为什么这会影响存储过程?

最后一件事,这个问题之后,从PHPMyAdmin

浏览帖子table时又出现了另一个问题

posts table browsing error

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

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

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);[=41 之后调用此函数=]

    $query->closeCursor();

希望此解决方案对您有所帮助