我在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);
}
}
Run Code Online (Sandbox Code Playgroud)
后来我打电话给:
$products=new Products();
echo $products->getAllProducts(Products::ORDER_BY_PRICE);
Run Code Online (Sandbox Code Playgroud)
为什么不在命令中使用:orderBy参数?