2012-02-02 116 views
0

查询结果有问题。在第一次调用函数时,getSales()函数效果很好。再次调用时,查询不会产生任何结果。这是一个很小的代码块:PDO - 查询未返回结果

abstract class Reporting { 
     protected function connect() { 
      try { 
       $this->dbh = PDOConnection::getInstance(); 

       if (!$this->dbh instanceof PDO) { 
        throw new CustomException('Unable to connect to database'); 
       } 
      } 
      catch (CustomException $e) { 
       echo $e; 
      } 
     } 
} 
class TenMinuteSales extends Reporting { 

     protected $date; 

     public function __construct($date) { 
      $this->date = new DateTime($date); 
      $this->date = $this->date->format('Y-m-d'); 
     } 

     public function beginReport() { 
      parent::connect(); 
     } 

     public function getSales($meridiem, $date) { 
      try { 
       $statement = "SELECT directory.location, IFNULL(sales.daily_sales,0.00) AS sales, IFNULL(sales.cover_counts,0) AS covers 
           FROM t_directory directory 
           LEFT JOIN v_sales_all sales 
           ON sales.site_id = directory.site_id 
           AND sales.business_date = :date 
           AND sales.meridiem = :meridiem 
           ORDER BY directory.site_id ASC 
           LIMIT :totalLocations"; 

       $sth = $this->dbh->prepare($statement); 
       $sth->bindParam(':date', $date, PDO::PARAM_STR); 
       $sth->bindParam(':meridiem', $meridiem, PDO::PARAM_STR); 
       $sth->bindParam(':totalLocations', $this->totalLocations, PDO::PARAM_INT); 
       $sth->execute(); 

       switch ($meridiem) { 
        case 'AM': 
         $this->amSales = $sth->fetchAll(PDO::FETCH_ASSOC); 
         return $this->amSales; 
        case 'PM': 
         $this->pmSales = $sth->fetchAll(PDO::FETCH_ASSOC); 
         return $this->pmSales; 
       } 
      } 
      catch (CustomException $e) { 
       echo $e; 
      } 
     } 

$tms = new TenMinuteSales($date); 
$tms->beginReport(); 
$amSales = $tms->getSales('AM', $date); 
$pmSales = $tms->getSales('PM', $date); 

当我打电话getSales()为上午或下午的销售数字,该函数成功返回的数据。当我第二次调用它时,函数不会返回任何数据。不知道我是否需要释放结果或其他方面的内容。我试过unset($sth)$sth->closeCursor(),其中没有一个似乎解决了我的问题。任何帮助解决我的问题将不胜感激。请让我知道是否需要更多细节。

+0

据我所见,'$ this-> totalLocations'没有定义,并且可能是NULL,是否正确? – Wrikken 2012-02-02 18:29:39

+0

我没有在其中设置代码。为了这个问题的目的。 '$ this-> totalLocations' = 20 – Brett 2012-02-02 18:31:40

+0

与您的问题无关,但您似乎在滥用try/catch。你在getSales()中的catch不会发生,因为没有任何东西被扔到那个级别。 – Kenaniah 2012-02-02 18:32:38

回答

1

由于这还不是全部的代码,通过参考给一个变量,这可能会导致意外的行为,如果你不付出非常密切地关注碰巧这些变量后一切要注意->bindParam工作是非常重要的上。如果您不明确需要参考,则使用->bindValue(其名称以变量的值绑定变量)更安全,更简单,而且最重要的是更清晰。显然这工作在这里,但确切地说为什么很难说没有完整的代码;)

+0

再次感谢。我无法相信我忽略了'bindParam' – Brett 2012-02-02 19:34:49