开发者

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

开发者 https://www.devze.com 2023-01-01 13:17 出处:网络
I\'mhaving 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. Whe

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

精彩评论

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