开发者

Why doesn't binding parameter in ORDER BY clause order the results?

I'm having problem with binding a parameter in an ORDER BY clause within a PDO statement. "orderBy" doesn't seems to be passed to the query as results are not ordered as they're suppose to be. When I use a column name such as price in the query rather than a parameter, the results are sorted by that column. The code is:

class Products {
    const ORDER_BY_NAME='name';
    const ORDER_BY_PRICE_PER_UNIT='price_per_unit';
    const ORDER_BY开发者_运维百科_PRICE='price';
    const ORDER_BY_MINIMUM_QUANTITY='minimum_quantity';

    // function returns array of all products

    public function getAllProducts($orderBy) { 
        $db=Registry::getVariable('db');
        $pdoStatement=$db->prepare("SELECT name, minimum_quantity, price_per_unit, price, id FROM products ORDER BY :orderBy;");
        $pdoStatement->bindParam(':orderBy', $orderBy, PDO::PARAM_STR);
        $pdoStatement->execute();
        return $pdoStatement->fetchAll(PDO::FETCH_ASSOC);
    }
}

Later on I call:

 $products=new Products();

 echo $products->getAllProducts(Products::ORDER_BY_PRICE);

Why doesn't the :orderBy parameter seem to be used in query?


Parameter binding is intended to be used with values. ORDER BY is actually followed by a field name, not a string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜