PHP5 MySql和PDO异常

sam*_*azi 6 php mysql pdo

我在使用PDO与PHP5.4和MySql时遇到了异常.

我已经阅读了几乎所有其他帖子,博客,手册,片段,我可以与此错误相关的所有内容,并尝试了我所看到的一切,但没有运气.

所以我希望它特定于我在特定代码中做错的事情,你可以向我指出.

这是错误:

SQLSTATE [HY000]:常规错误:2014在其他未缓冲的查询处于活动状态时无法执行查询.考虑使用PDOStatement :: fetchAll().或者,如果您的代码只是针对mysql运行,则可以通过设置PDO :: MYSQL_ATTR_USE_BUFFERED_QUERY属性来启用查询缓冲.

以下是导致此错误的代码部分:

第一部分:

        $stmt = $this->dbConn->prepare("CALL getPopularProducts()");
        $stmt->execute();
        $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        //$stmt->closeCursor();

        foreach ($rows as $row) {
            $p = new entity\LightingPole();
             /* doing basic set stuff here so code omitted */

            // apply category to product
            $categroyTranslator = new ProductCategoryTranslator();
            $categroyTranslator->applyProductCategory($p);
Run Code Online (Sandbox Code Playgroud)

第二部分:

        public function applyProductCategory(entity\Product $product) {
            $productId = $product->getProductId();
            try {
               /** exception thrown on this line **/
               $stmt = $this->dbConn->prepare("CALL getCategoryByProductId(?)"); 

               $stmt->bindParam(1, $productId, \PDO::PARAM_INT);
               $stmt->execute();

               while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)){
                   $category = new entity\ProductCategory();

                   $product->setCategory($category);
               }  
             }
             catch (\PDOException $e) {
                 echo $e->getMessage();
                 print($e->getTraceAsString());
             }
         }
Run Code Online (Sandbox Code Playgroud)

这是我的数据库类:

namespace lib\database;

class Database
{
    protected static $instance;

    public static function getInstance()
    {
        if(self::$instance == null)
        {
            $dsn = "mydsn";
            $user = "myuser";
            $password = "mypassword";
            self::$instance->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
            self::$instance->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
            self::$instance->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        }
        return self::$instance;
    }

    private function __construct() {}

    private function __clone() {}
}
Run Code Online (Sandbox Code Playgroud)

你可能会注意到我有一个$stmt->closeCursor()我已经评论过的电话.当我包含这行代码时,我收到以下错误:

SQLSTATE [HY000]:一般错误:2006 MySQL服务器已经消失

现在用简单的功能术语来解释它,我在这里基本上做的是获得流行产品的列表,循环它们并获得所有相关的产品数据,如ProductCategory等......

所以这个错误只发生在循环中的第一个产品,即我第二次调用applyProductCategory()它工作正常,没问题.另一件事是,下面applyProductCategory大约有4个调用来检索其他类型的关联数据,并且在执行此操作时也不会抛出任何错误.

所以最后,我所有受欢迎的产品都很好,除了第一个产品从未有过与之相关的ProductCategory.

期待找到我错过的原因导致这一点.希望你能指出我正确的方向.

Faj*_*hos 2

尝试在抛出错误之前使用 unset($stmt)

    unset($stmt);
    $stmt = $this->dbConn->prepare("CALL getCategoryByProductId(?)");  
Run Code Online (Sandbox Code Playgroud)

我之前遇到过同样的错误,并因某种原因修复了它。我之前在这里找到了答案PDO 无缓冲查询