2017-07-15 38 views
0

考慮下面的查詢返回預期的結果不工作:PHP MySQL的ORDER BY,因爲它應該

SELECT * FROM `articles` ORDER BY article_date DESC 

但在PHP中的結果仍下令ASC。

<?php 
header("Content-Type:application/json"); 
require_once('connection.php'); 

$sql = "SELECT article_name, article_text, article_date FROM articles ORDER BY article_date DESC"; 
$result = mysqli_query($conn, $sql); 

$result_array = array(); 
$rows = array(); 

if (mysqli_num_rows($result) > 0) { 
    while($row = mysqli_fetch_assoc($result)) { 
     $rows[] = $row; 
    } 
} 

http_response_code(200); 
$result_array['status'] = 200; 
$result_array['error'] = ""; 
$result_array['result'] = $rows; 

exit(json_encode($result_array)); 
?> 

我嘗試了不同的方法,如DATE_FORMAT或更改字段的類型timestamp類型。

我的文章表看起來像這樣:

CREATE TABLE `articles` (
    `id` int(11) NOT NULL, 
    `article_name` varchar(255) NOT NULL, 
    `article_text` text NOT NULL, 
    `article_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP 
) ENGINE=MyISAM DEFAULT CHARSET=latin1; 

有沒有人有任何想法,爲什麼出現這種情況?

+1

您的觀察結果與您向我們展示的查詢不一致。你確定這是實際導致升序結果集的查詢和代碼嗎? –

+0

問題是'json_encode'在這裏看到答案:[Json_encode改變我的查詢順序](https://stackoverflow.com/questions/20693404/json-encode-changing-the-order-of-my-query ) – Atmahadli

+0

有趣的,謝謝@Atmahadli我會更多地挖掘這個。 –

回答

1

首先,我會假設你的ID是自動遞增的,這意味着它將按ID的時間順序排列,因爲在每個帖子後,ID會增加1。所以我建議的是這樣的:

$sql = "SELECT * FROM articles ORDER BY id DESC"; 
$result = mysqli_query($conn, $sql); 

如果這樣行不通,告訴我,我會幫你。

+0

您現在假定文章按日期順序輸入。但我今天可以寫出關於上週所有比賽的故事,而不是按順序執行 –

+0

@IvoP在他的SQL代碼中,您可以看到他將當前時間戳插入到他的表中,這意味着它將按日期順序輸入並且ID會起作用。 – HoogleyBoogley