PHP5 MySql和PDO异常

时间:2012-09-25 00:17:52

标签: 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);

第二部分:

        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());
             }
         }

这是我的数据库类:

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() {}
}

你可能会注意到我已经注释了$stmt->closeCursor()的电话。当我包含这行代码时,我收到以下错误:

  

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

现在用简单的功能术语解释一下,我在这里基本上做的是获取热门产品列表,循环浏览它们并获取所有相关的产品数据,如ProductCategory等......

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

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

期待找到我错过的原因。希望你能指出我正确的方向。

1 个答案:

答案 0 :(得分:2)

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

    unset($stmt);
    $stmt = $this->dbConn->prepare("CALL getCategoryByProductId(?)");  

之前我遇到了同样的错误,并且由于某种原因修复了它。我之前在PDO Unbuffered queries

找到了答案