dongyi7669 2018-11-21 13:46
浏览 76
已采纳

无法在SELECT字段名称中使用BindValue? [重复]

This question already has an answer here:

I have a MySQL database containing Countries

id  | de          | en          | fr   
--------------------------------------------- 
 1  | Afghanistan | Afghanistan | Afghanistan
 2  | Albanien    | Albania     | Albanie
...

I'd like to get a list of the countries, according to visitor's language.

Here's the method in my class :

public function getList($language){
    $countries = array();
    $req = ('SELECT id, :language FROM country ORDER BY :language ASC');        
    $q = $this->_db->prepare($req);
    $q->bindValue(':language', $language, \PDO::PARAM_STR);
    $q->execute();
    while ($data = $q->fetch(\PDO::FETCH_ASSOC)) {
        $countries[] = new Country($data);
    }
    return $countries;
    $q->closeCursor();
}

It returns an array, but country names are replaced by the language.

It seems bindValue is adding quotes to my variable, which is fine in the ORDER BY, but creates problems in the fields i want to SELECT.

$countryManager->getList('fr');

returns something like this

Array
(
[0] => Entities\Country Object
    (
        [id:Entities\Country:private] => 1
        [de:Entities\Country:private] =>  
        [en:Entities\Country:private] => 
        [fr:Entities\Country:private] => fr
    )

[1] => Entities\Country Object
    (
        [id:Entities\Country:private] => 2
        [de:Entities\Country:private] => 
        [en:Entities\Country:private] => 
        [fr:Entities\Country:private] => fr
    )

If you have any idea on where the problem might be, i'd be very glad to know :)

Thank you in advance for your help.

</div>
  • 写回答

1条回答 默认 最新

  • dpe77294 2018-11-21 13:52
    关注

    You can't use prepared statements to set the names of columns or tables in a query, you can only use them to inject values. You'll have to use string interpolation

    Don't forget to apply thorough validation to prevent SQL injection vulnerabilities.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog