PDO命令抛出错误

时间:2013-01-26 08:17:28

标签: php pdo

我很困惑。

这是有效的:

$sql = 'SELECT * FROM TABLE ORDER BY DATEOFUPLOAD DESC'; 
$stmt = $conn->prepare($sql); 
$stmt->execute();

这不是:

$sql = 'SELECT * FROM TABLE ORDER BY DATEOFUPLOAD :orderbydateofupload'; 
$stmt = $conn->prepare($sql); 
$stmt->bindValue(':orderbydateofupload', $orderbydateofupload, PDO::PARAM_STR);  
$stmt->execute();

我已经$orderbydateofupload检查并设置了$orderbydateofupload='DESC',所以它绝对不是空的。

我收到错误到最后一行($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 ''DESC'' at line 1' in /home/gh6534/public_html/query.php:77 Stack trace: #0 /home/gh6534/public_html/query.php(77): PDOStatement->execute() #1 {main} thrown in /home/gh6534/public_html/query.php on line 77

我还尝试将列用作参数:

$sort = 'DATEOFUPLOAD';
$sql = 'SELECT * FROM TABLE ORDER BY :sort :orderbydateofupload'; 
$stmt = $conn->prepare($sql); 
$stmt->bindParam(':sort', $sort);
$stmt->bindParam(':orderbydateofupload', $orderbydateofupload);
$stmt->execute(); 

这不会引发异常,但会查询所有项目而不进行任何排序。怎么了?

2 个答案:

答案 0 :(得分:2)

试试这个

$orderbydateofupload = 'ASC';  //Or DESC

if($orderbydateofupload == 'DESC')
    $sql = 'SELECT * FROM TABLE ORDER BY DATEOFUPLOAD DESC'; 
else
    $sql = 'SELECT * FROM TABLE'

答案 1 :(得分:1)

您无法将标识符与PDO绑定,因为预准备语句只能用于数据,而不能用于标识符或语法关键字。
因此,您必须使用白名单,如example I posted before

所示

这就是为什么在我自己的类中我使用标识符占位符,它将整个代码放在一行(当你需要按字段设置顺序时):

$data = $db->getAll('SELECT * FROM TABLE ORDER BY ?n',$sort); 

但使用关键字白名单是唯一的选择:

$order = $db->whiteList($_GET['order'],array('ASC','DESC'),'ASC');
$data  = $db->getAll("SELECT * FROM table ORDER BY ?n ?p", $sort, $order);