Why does backticks fails in PDO query? [duplicate]

走远了吗. 提交于 2019-12-12 03:14:31

问题


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?

ex:

    $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.';
    }

In the log, with backticks:

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

Without backticks:

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

回答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);


来源:https://stackoverflow.com/questions/28477730/why-does-backticks-fails-in-pdo-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!