PDO准备语句限制不起作用

时间:2013-06-28 02:35:49

标签: php

我试图限制从SQL查询返回的结果数量,但由于某种原因它返回NULL。如果我删除LIMIT,一切正常。我在Sequel Pro中测试了这个查询,它也适用于LIMIT。我在这里做错了吗?

 public static function getMostViewedPictures($limit = 5) {
    $dbh = self::connectToDatabase();

    $sql = "SELECT 
                picture.`title`, 
                picture.`description`,
                picture.`slug`,
                picture.`image`,
                picture.`timestamp`,
                picture.`views`,
                category.category as category
            FROM picture 
            LEFT JOIN category 
                ON picture.category_id = category.id
            ORDER BY picture.views ASC
            LIMIT 0, :limit";

    $sth = $dbh->prepare($sql);
    $sth->execute(array(':limit' => $limit));

    if($results = $sth->fetchAll(PDO::FETCH_OBJ)) {
        $pictures = array();

        foreach($results as $result) {
            $pictures[] = new Picture(
                $result->title,
                $result->description,
                $result->slug,
                $result->timestamp,
                $result->category,
                $result->views,
                $result->image
            );
        }

        return $pictures;
    } else {
        return null;
    }
}

1 个答案:

答案 0 :(得分:5)

解决。

$sth->bindParam(':limit', $limit, PDO::PARAM_INT);