PDO - 查询不返回结果

时间:2012-02-02 18:27:27

标签: php mysql oop pdo

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

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

当我为AM或PM销售号码呼叫getSales()时,该功能成功返回数据。当我第二次调用它时,该函数不会返回任何数据。不确定我是否需要释放结果或其他内容。我尝试了unset($sth)$sth->closeCursor(),但似乎都没有解决我的问题。任何帮助修复我的问题将不胜感激。如果需要更多详细信息,请与我们联系。

1 个答案:

答案 0 :(得分:1)

由于这不是整个代码,因此请务必注意->bindParam通过引用对变量起作用,如果您没有非常密切关注,可能会导致意外行为以后发生在那些变量上的所有事情。如果您没有明确需要引用,则使用->bindValue(正如名称所示,按值绑定变量)更安全,更容易,而且最重要的是更清晰。显然这可以在这里工作,但确切为什么很难说没有完整的代码;)