简体   繁体   中英

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.

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".

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM