考虑下面的查询返回预期的结果不工作: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;
有没有人有任何想法,为什么出现这种情况?
您的观察结果与您向我们展示的查询不一致。你确定这是实际导致升序结果集的查询和代码吗? –
问题是'json_encode'在这里看到答案:[Json_encode改变我的查询顺序](https://stackoverflow.com/questions/20693404/json-encode-changing-the-order-of-my-query ) – Atmahadli
有趣的,谢谢@Atmahadli我会更多地挖掘这个。 –