[英]PDO order by throws error
I am confused. 我很困惑。
This is working: 这是有效的:
$sql = 'SELECT * FROM TABLE ORDER BY DATEOFUPLOAD DESC';
$stmt = $conn->prepare($sql);
$stmt->execute();
This is not: 这不是:
$sql = 'SELECT * FROM TABLE ORDER BY DATEOFUPLOAD :orderbydateofupload';
$stmt = $conn->prepare($sql);
$stmt->bindValue(':orderbydateofupload', $orderbydateofupload, PDO::PARAM_STR);
$stmt->execute();
I have checked and set $orderbydateofupload
by $orderbydateofupload='DESC'
, so it's definitely not null. 我已经通过
$orderbydateofupload='DESC'
检查并设置$orderbydateofupload
,所以它绝对不是null。
I get an error to the last line ( $stmt->execute()
): 我在最后一行收到错误(
$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
I also tried to use the column as parameter: 我也尝试使用列作为参数:
$sort = 'DATEOFUPLOAD';
$sql = 'SELECT * FROM TABLE ORDER BY :sort :orderbydateofupload';
$stmt = $conn->prepare($sql);
$stmt->bindParam(':sort', $sort);
$stmt->bindParam(':orderbydateofupload', $orderbydateofupload);
$stmt->execute();
This does not throw an exception, but all items are queried without any sorting. 这不会引发异常,但会查询所有项目而不进行任何排序。 What's wrong?
怎么了?
Try this 尝试这个
$orderbydateofupload = 'ASC'; //Or DESC
if($orderbydateofupload == 'DESC')
$sql = 'SELECT * FROM TABLE ORDER BY DATEOFUPLOAD DESC';
else
$sql = 'SELECT * FROM TABLE'
You can't bind identifiers with PDO because prepared statements can be used only with data , but not with identifiers or syntax keywords. 您不能将标识符与PDO绑定,因为预准备语句只能用于数据 ,而不能用于标识符或语法关键字。
So, you have to use whitelisting , as shown in the example I posted before 因此,您必须使用白名单 ,如我之前发布的示例所示
That's why in my own class I use identifier placeholder, which makes whole code into one line (when you need to set the order by field only): 这就是为什么在我自己的类中我使用标识符占位符,它使整个代码成一行(当你需要按字段设置顺序时):
$data = $db->getAll('SELECT * FROM TABLE ORDER BY ?n',$sort);
but with keywords whitelisting is the only choice: 但使用关键字白名单是唯一的选择:
$order = $db->whiteList($_GET['order'],array('ASC','DESC'),'ASC');
$data = $db->getAll("SELECT * FROM table ORDER BY ?n ?p", $sort, $order);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.