Chuck Le Butt
Chuck Le Butt

Reputation: 48758

MySQL/PDO: Select different columns depending on parameters

I have a MySQL query that needs to change depending on what parameters are being passed to it. Sounds simply enough, right? The problem is that if the parameter is '0' I need it to grab ALL the records.

How can I do this?

Here's what I have so far.

public function getLatestWork($numberOfSlides, $type = 0) {

    $params = array();
    $params["numberOfSlides"] = $numberOfSlides;
    $params["type"] = $type;

    $STH = $this->_db->prepare("SELECT slideID 
        FROM slides
        WHERE visible = 'true'
            AND type = :type
        ORDER BY order
        LIMIT :numberOfSlides;");

    $STH->execute($params);

    $result = $STH->fetchAll(PDO::FETCH_COLUMN);

    return $result;        
}

Update: $numberOfSlides is independent of the problem. It will always return a set number of results. It's all about $type: If it's set to '0' (the default) then it essentially ignores that part of the WHERE statement. If it's set to '1' or '2', etc., then it only pulls records of that type.

Obviously I could just change the value of $STH depending on the value of $type, but I was wondering if there was a better way.

Upvotes: 0

Views: 202

Answers (2)

Michał Powaga
Michał Powaga

Reputation: 23183

I would use nullif and ifnull functions:

SELECT slideID 
FROM slides
WHERE visible = 'true'
    AND ifnull(nullif(:type, 0), type) = type
ORDER BY "order"
LIMIT :numberOfSlides;

If :type is 0 then nullif returns null, and if nullif returns null ifnull returns value from type column so if you pass :type = 0 the result will be type = type - means "all rows".

Upvotes: 2

Rawkode
Rawkode

Reputation: 22592

public function getLatestWork($numberOfSlides, $type = 0) {
    $params = array();
    $params["numberOfSlides"] = $numberOfSlides;
    $params["type"] = $type;

    $STH = $this->_db->prepare("SELECT slideIDFROM slides WHERE visible = 'true' "
               . ($type > 0 ? "AND type = :type" : "") 
               . " ORDER BY order LIMIT :numberOfSlides;");

    $STH->execute($params);

    $result = $STH->fetchAll(PDO::FETCH_COLUMN);

    return $result;        
}

Upvotes: 1

Related Questions