2

I'm attempting to limit the amount of results returned from an SQL query, but for some reason it's returning NULL. If I remove the LIMIT, all works fine. I've tested the query in Sequel Pro and it also works fine with the LIMIT. Am I doing something wrong here?

 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;
    }
}
James Jeffery
  • 12,093
  • 19
  • 74
  • 108
  • 1
    see also [PDO prepared statement causes an error in LIMIT statement](http://stackoverflow.com/a/15991623/689579) – Sean Jun 28 '13 at 02:43
  • Also check out http://stackoverflow.com/questions/2269840/php-pdo-bindvalue-in-limit – j08691 Jun 28 '13 at 02:45

1 Answers1

10

Solved.

$sth->bindParam(':limit', $limit, PDO::PARAM_INT);
James Jeffery
  • 12,093
  • 19
  • 74
  • 108