skip to Main Content
$query = "CALL GetAllCategories()";
$stmt = $pdo->prepare($query);
$stmt->execute();
$categories = $stmt->fetchAll();

I use this code to get categories from DB using stored procedures, no problems with that, everything works fine.

This is GetAllCategories() procedures:

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

After that, I used regular SQL statement to get posts ( for testing, I will use stored procedure for that )

this is the query to get posts:

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`;

From here the problem occurred:

error image

this error appears:

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:xampphtdocscmsindex.php:17 Stack trace: #0 C:xampphtdocscmsindex.php(17): PDO->prepare('SELECTn `p`....') #1 {main} thrown in C:xampphtdocscmsindex.php on line 17

When trying several attempts, I change the GetAllCategories() stored procedure to reqular query statement:

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

The problem disappeared

Can anyone explain why this happed with stored procedures?

The last thing, After this issue, another problem appeared in the posts table when browsing it from PHPMyAdmin

posts table browsing error

2

Answers


  1. Chosen as BEST ANSWER

    I used $stmt->closeCursor(); after fetching data from GetAllCategories() stored procedure to solve this error.

    $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

    This error is always happens while there were two executions at a same time for example:

    1. CASE 1

      if(!$query->execute())

      die("SQL FAILED");
      

      else

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

    Solution: Second execution is no needed, remove second one, the first execution is already executed.

    1. if the first case is not working, USE this Solution call this function after $query=$handler->prepare($sql);

      $query->closeCursor();

    I hope this Solution is helpful

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search