为什么在ORDER BY子句中的绑定参数不对结果排序? [英] Why doesn't binding parameter in ORDER BY clause order the results?

查看:80
本文介绍了为什么在ORDER BY子句中的绑定参数不对结果排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在绑定PDO语句中的ORDER BY子句中的参数时遇到问题. "orderBy"似乎没有传递给查询,因为结果没有按照预期的那样进行排序.当我在查询中使用诸如price之类的列名而不是参数时,结果将按该列排序.代码是:

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

稍后致电:

 $products=new Products();

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

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

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

推荐答案

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

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

这篇关于为什么在ORDER BY子句中的绑定参数不对结果排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆