为什么反引号在 PDO 查询中失败?
Why does backticks fails in PDO query?
我有一个 table 名称中有连字符,我无法更改 table 名称,所以我认为反引号会有所帮助。
不幸的是,它失败了,一些谷歌搜索没有给我任何答案。我该如何解决?
例如:
$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
如果需要注入table名字,不能作为绑定变量来做;只要该值已列入白名单,就可以使用
$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);
我有一个 table 名称中有连字符,我无法更改 table 名称,所以我认为反引号会有所帮助。
不幸的是,它失败了,一些谷歌搜索没有给我任何答案。我该如何解决?
例如:
$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
如果需要注入table名字,不能作为绑定变量来做;只要该值已列入白名单,就可以使用
$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);