【问题标题】:Why doesn't binding parameter in ORDER BY clause order the results?为什么 ORDER BY 子句中的绑定参数不对结果进行排序?
【发布时间】:2010-05-25 19:06:06
【问题描述】:

我在 PDO 语句的 ORDER BY 子句中绑定参数时遇到问题。 “orderBy”似乎没有传递给查询,因为结果没有像他们想象的那样排序。当我在查询中使用price 之类的列名而不是参数时,结果将按该列排序。代码是:

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

稍后我会打电话:

 $products=new Products();

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

为什么查询中似乎没有使用 :orderBy 参数?

【问题讨论】:

    标签: php sql mysql pdo


    【解决方案1】:

    参数绑定旨在与值一起使用。 ORDER BY 后面实际上是一个字段名,而不是字符串。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多