Reputation: 2876
Given the following query that returns the expected results:
SELECT * FROM `articles` ORDER BY article_date DESC
but in PHP the results are still ordered 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));
?>
I've tried different approaches like DATE_FORMAT
or changing the type of the field to timestamp
type.
My articles table looks like this:
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;
Does anyone have any idea why this happens?
Upvotes: 0
Views: 79
Reputation: 340
First off, I would assume that your ID would be auto-increment, meaning that it would be in chronological order by the ID because after every post, a the ID would increase by one. So what I would suggest is this:
$sql = "SELECT * FROM articles ORDER BY id DESC";
$result = mysqli_query($conn, $sql);
If that doesn't work, tell me and I will help you out.
Upvotes: 1