2017-07-15 39 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