为什么反引号在PDO查询中失败? [英] Why does backticks fails in PDO query?

查看:100
本文介绍了为什么反引号在PDO查询中失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名称中带有连字符的表格,并且我不能更改表格名称,所以我认为反引号会有所帮助.

I have a table with hyphens in the name, and I can't change the table name so I thought backticks would help.

不幸的是,它失败了,一些谷歌搜索没有给我任何答案.我该如何解决?

Unfortunally for me it failed, some googling did'nt give me any answers. How can I solve this?

例如:

    $stmt = $this->_dbh->prepare(
        'UPDATE `:table`
        SET status = NOT status
        WHERE id=:id;');


    $stmt->bindParam(':table',$this->_settings['table'], PDO::PARAM_STR);
    $stmt->bindParam(':id',$data['id'], PDO::PARAM_INT);
    if( $stmt->execute() ){
        return 'Success';
    }
    else{
        $this->_log( $stmt->errorInfo() );
        return 'Action failed.';
    }

在日志中,带反引号:

13:25:18    42S02
1146
Table 'db_name.'table-name'' doesn't exist

没有反引号:

13:38:14    42000
1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''table-name'
            SET status = NOT status
            WHERE id='1'' at line 1

推荐答案

如果需要注入表名,则不能将其作为绑定变量来使用.只要该值已列入白名单,您就可以使用

If you need to inject the table name, you can't do it as a bind variable; as long as the value has been whitelisted, you can use

$stmt = $this->_dbh->prepare(
        sprint(
            'UPDATE `%s`
                SET status = NOT status
              WHERE id=:id;',
            $this->_settings['table']
        )
    );


$stmt->bindParam(':id',$data['id'], PDO::PARAM_INT);

这篇关于为什么反引号在PDO查询中失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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