2012-02-02 115 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