Greg
Greg

Reputation: 193

PDO Prepared Statement Query Not Following WHERE

/**
 * Query the database, and grab a random banner.
 *
 * @return object Database row.
 */
protected function getRandomBanner()
{
    try 
    {
        $stmt = $this->db->prepare("SELECT * FROM banners WHERE Type=:type BETWEEN Start AND End ORDER BY RAND() LIMIT 1");
        $stmt->execute(array(':type' => $this->type));
        return $stmt->fetch(PDO::FETCH_OBJ);
    } catch (PDOException $e) {
        echo $e->getMessage();
    }
}

This code is part of a class. It querys the DB to display banner ads based on simple query string display_banner.php?banner_type=leaderboard. It works perfectly.

However, I want to include "BETWEEN" so it can check against the banner Start Date and End Date.

Again, this query runs - and banners display! However...When I added "BETWEEN" it no longer followed "Type". Now, it shows rectangles AND leaderboards. What's crazy, is in phpMyAdmin when I run this query, it works perfectly.

Upvotes: 0

Views: 44

Answers (1)

hjpotter92
hjpotter92

Reputation: 80639

You need to compare the current date, then you must have NOW() to check against.

SELECT * 
FROM banners 
WHERE Type=:type 
    AND NOW() BETWEEN Start AND End 
ORDER BY RAND() 
LIMIT 1

Upvotes: 2

Related Questions