【发布时间】: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 参数?
【问题讨论】: