2012-09-08 36 views
1

在phpMyAdmin,我可以通过SQL运行此:PHP PDO在他们的名字选择用单引号列

SELECT * FROM mytable WHERE `Bob's Stuff` > 1 

但是,当我运行完全相同的查询PHP脚本:

$stmt->prepare("SELECT * FROM mytable WHERE `Bob's Stuff` > :int"); 
$stmt->bindValue(':int', $int); 
$stmt->execute(); 

我得到这个错误:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 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 ':int AND Bob's Stuff >= '1')' at line 10' in script.php:208 Stack trace: #0 script.php(208): PDOStatement->execute() #1 {main} thrown in script.php on line 208

如果我将查询列更改为任何其他列名称,查询工作正常。

是否有可能具有撇号的列名?

+3

恕我直言,有一个列或一个表中用撇号命名是错误的... –

回答

0

也作出这样的列名作为参数,

$tableName = "`Bob\'s Stuff`"; 
$stmt->prepare("SELECT * FROM mytable WHERE :tableName > :int"); 
$stmt->bindValue(':tableName', $tableName); 
$stmt->bindValue(':int', $int); 
$stmt->execute(); 

顺便说一句,一个建议是下一次不喜欢Bob's Stuff创建列。让它像这样的单个词BobStuff

+4

Mysql不支持绑定标识符,如字段或表名称。这是字面上使用的比较值,使其成为一个常数吨。 – ircmaxell