1

我很困惑。

这是有效的:

$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(); 

这不会引发异常,但会在没有任何排序的情况下查询所有项目。怎么了?

4

2 回答 2

2

试试这个

$orderbydateofupload = 'ASC';  //Or DESC

if($orderbydateofupload == 'DESC')
    $sql = 'SELECT * FROM TABLE ORDER BY DATEOFUPLOAD DESC'; 
else
    $sql = 'SELECT * FROM TABLE'
于 2013-01-26T08:25:52.770 回答
1

您不能将标识符与 PDO 绑定,因为准备好的语句只能与 data 一起使用,而不能与标识符或语法关键字一起使用。
因此,您必须使用whitelisting,如我之前发布的示例所示

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

$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);
于 2013-01-26T08:31:01.220 回答