在我的情况下如何对记录进行排序(排序依据)

时间:2019-06-06 11:40:48

标签: php sql sql-order-by

嗨,我正在尝试按数据对我的比赛进行排序,但是出了点问题,我不知道在代码中将ORDER BY data DESC放在哪里。

当我有时间的数据时,

data是我表中的一个池。如果我将data_in放在行尾,那么当我放置2个数据(data_in data_out)时代码会停止工作,我也将WHERE 1=1放在后面并也停止工作,那么该怎么做?

$query = "SELECT * FROM database WHERE 1=1 ";   

if ($name != ''){
    $query.=" and name like '%$name%' ";
}

if ($number != ''){
    $query.=" and number like '%$number%' ";
}

if ($person != ''){
    $query.=" and person like '%$person%' ";
}

if ($data_in != ''){
    $query.=" and data_in >= '{$data_in} 00:00:00'::timestamp ";
}

if ($data_out != ''){
    $query.=" and data_out <= '{$data_out} 23:59:00'::timestamp ";
}

if ($case != ''){
    $query.=" and case like '%$case%' ";
}           

$result = pg_query($query);

4 个答案:

答案 0 :(得分:0)

首先,您不应添加1 = 1,因为它将显示所有记录。您可以删除它。之后,如果满足以下条件,则可以按顺序添加订单:

$query = "SELECT * FROM database WHERE ";   
$whereQuery = [];
if ($name != ''){
        $whereQuery[] = " name like '%$name%' ";}

if ($number != ''){
        $whereQuery[] =" number like '%$number%' ";}

if ($person != ''){
        $whereQuery[] =" person like '%$person%' ";}
if ($data_in != ''){
        $whereQuery[] =" data_in >= '{$data_in} 00:00:00'::timestamp ";}
if ($data_out != ''){
        $whereQuery[] =" data_out <= '{$data_out} 23:59:00'::timestamp ";}
if ($case != ''){
        $whereQuery[] =" case like '%$case%' ";}           

$completeQuery = $query.implode(" and ", $whereQuery)." order by data";  
$result = pg_query($completeQuery);

此外,您的查询已打开以进行SQL注入。除了绑定变量,还应该绑定变量。

希望对您有帮助!

答案 1 :(得分:0)

单独一行,位于$result = ...行之前:

$query .= " ORDER BY data DESC "

答案 2 :(得分:0)

您可以通过在条件之后和使用pg_query()之前放置“ ORDER BY”来按数据排序。 您可以使用以下代码。

$query = "SELECT * FROM database WHERE 1=1 ";   

if ($name != ''){
        $query.=" and name like '%$name%' ";}

if ($number != ''){
        $query.=" and number like '%$number%' ";}

if ($person != ''){
        $query.=" and person like '%$person%' ";}
if ($data_in != ''){
        $query.=" and data_in >= '{$data_in} 00:00:00'::timestamp ";}
if ($data_out != ''){
        $query.=" and data_out <= '{$data_out} 23:59:00'::timestamp ";}
if ($case != ''){
        $query.=" and case like '%$case%' ";}           

$query.="ORDER BY data_in DESC";
        $result = pg_query($query);

答案 3 :(得分:0)

所有子句的结尾(如果是where子句)

  $query.=" and case like '%$case%' ";}           

  $query.="  order by  my_column1, my_column2 ,  ,,, my_last_col ";}     

  $result = pg_query($query);