考慮下面的查詢返回預期的結果不工作: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我會更多地挖掘這個。 –