2015-05-07 95 views
1

我使用多個查詢,它工作正常,我面臨的唯一問題是,順序是不工作。我嘗試了一些代碼,如ORDER BY不能與MySQL多個查詢

$query = "SELECT id, name, reg_number, class, section FROM register where id IS NOT NULL ORDER BY `id` DESC"; 

它在phpmyadmin中工作正常,並給我一個正確的結果。但它不能在我想使用它的地方工作。

$query = "SELECT id, name, reg_number, class, section FROM register where id IS NOT NULL "; 

    if ($name !=""){ 
     $query .= " AND `name` LIKE '".$name."%'"; // id is greater then 
    } 

    if ($status !=""){ 
     $query .= " AND `status` LIKE '".$status."%'"; // id is greater then 
    } 

    if ($id_from !=""){ 
     $query .= " AND id >= $id_from "; // id is greater then 
    } 

    if ($id_to !=""){ 

     $query .= " AND id <= $id_to "; // id is shorter then 
    } 

     if ($class !=""){ 
     $query .= " AND class IN($class)"; // Selecting class 
    } 

    if ($section !=""){ 
     $query .= " AND section IN($section)"; // selecting section 
    } 

$result = mysql_query($query); 

我想在此查詢中使用order by,但order by不能使用this。

$query = "SELECT id, name, reg_number, class, section FROM register where id IS NOT NULL ORDER BY `id` DESC"; 

,並使用

$query = "SELECT id, name, reg_number, class, section FROM register where id IS NOT NULL ORDER BY id DESC"; 

我不知道什麼是我的代碼的問題。

+0

'的var_dump($查詢)''的$ result'行之前和你得到了什麼?從代碼看,如果你只是換出第一行,它看起來最終會成爲無效的SQL。 –

+1

您是否在ORDER BY之後附加了其他WHERE條件? ORDER BY必須在最後... – jarlh

+0

請[停止使用'mysql_ *'函數](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in -php)。他們不再被維護,並[正式棄用](https://wiki.php.net/rfc/mysql_deprecation)。瞭解[準備的陳述](http://en.wikipedia.org/wiki/Prepared_statement),並考慮使用PDO,[它不像你想象的那麼難](http://jayblanchard.net/demystifying_php_pdo.html) 。 –

回答

3

只需添加ORDER BY當完成您的WHERE

 if ($section !=""){ 
     $query .= " AND section IN($section)"; // selecting section 
    } 

$query .= " ORDER BY id DESC"; 
$result = mysql_query($query); 
+0

感謝亞歷克斯它工作正常,我與過去6小時的代碼戰鬥,我試過同樣的美元查詢。=「ORDER BY ID DESC」;但我之前嘗試過,如果條件,這就是爲什麼它不顯示任何結果.. 謝謝很多人.... – jitu