[英]Correct Syntax to Add ORDER BY to SQL Query
How can I add ORDER BY field
to the end of this SQL query $sql = "SELECT item_id,field FROM item WHERE department=".$catid;
如何将ORDER BY field
添加到此 SQL 查询的末尾$sql = "SELECT item_id,field FROM item WHERE department=".$catid;
? ? I can't get the syntax right due to the PHP variable at the end...由于最后的 PHP 变量,我无法获得正确的语法...
I tried $sql = "SELECT item_id,field FROM item WHERE department=".$catid ORDER BY field;
我试过$sql = "SELECT item_id,field FROM item WHERE department=".$catid ORDER BY field;
but obviously that didn't work但显然那没有用
You can fix your syntax error like this, using another concatenation operator .
您可以使用另一个连接运算符来修复这样的语法错误.
to append the ORDER BY
clause:附加ORDER BY
子句:
$sql = "SELECT item_id,field FROM item WHERE department=".$catid." ORDER BY field";
As long as $catid
is an integer, that will work, but it may leave you open to SQL injection , dependent on the source of the value in $catid
.只要$catid
是一个整数,它就可以工作,但它可能会让您接受SQL 注入,这取决于$catid
值的来源。
Best practice is to use a prepared query.最佳实践是使用准备好的查询。 For MySQLi
, something like this:对于MySQLi
,是这样的:
$sql = "SELECT item_id,field FROM item WHERE department=? ORDER BY field";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $catid); // change to 's' if $catid is a string
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with results
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.