在ORDER BY语句中使用php变量会产生错误

时间:2017-07-30 09:44:37

标签: php mysql mysqli

以下是我的疑问:

$sql = "SELECT date, status, reason 
        FROM tbl_attendance_mgmt ORDER BY date $order 
        LIMIT $number 
        WHERE fk_stu_id = '$stu_id'";

下面:

$order: ASC or DESC
$number: Number of rows to be displayed.

有人可以帮我解释为什么这个查询在执行时会给我错误吗?

3 个答案:

答案 0 :(得分:1)

您必须遵循sql查询的顺序。在{by} by order by

之前WHERE
$sql = "select `date`, status, reason from tbl_attendance_mgmt  where fk_stu_id = '$stu_id' order by `date` $order limit $number";

答案 1 :(得分:0)

以这种方式编写查询:

$sql = "SELECT date, status, reason 
        FROM tbl_attendance_mgmt
        WHERE fk_stu_id = '{$stu_id}' 
        ORDER BY date $order 
        LIMIT $number ";

你必须使用花括号{}

绑定你的php变量

答案 2 :(得分:0)

$sql = "SELECT date, status, reason 
FROM tbl_attendance_mgmt
WHERE fk_stu_id = " . mysqli_real_escape_string($con, $stu_id) . "
ORDER BY date $order 
LIMIT $number ";
  1. 你应该逃避你的变量
  2. 查询应按此顺序排列:SELECTFROMWHEREORDER BYLIMIT