【问题标题】:php mysql order by not working as it shouldphp mysql命令无法正常工作
【发布时间】:2017-12-20 11:32:23
【问题描述】:

给定以下返回预期结果的查询:

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 changing the order of my query
  • 有趣,谢谢@Atmahadli,我会进一步挖掘。

标签: php mysql


【解决方案1】:

首先,我假设您的 ID 将是自动递增的,这意味着它会按 ID 的时间顺序排列,因为在每次发布之后,ID 都会增加一个。所以我的建议是:

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

如果这不起作用,请告诉我,我会帮助你。

【讨论】:

  • 您现在假设文章是按日期顺序输入的。但我今天可以很好地写关于上周所有比赛的故事,而不是按顺序进行
  • @IvoP 在他的 SQL 代码中,您可以看到他正在将当前时间戳插入到他的表中,这意味着它将按日期顺序输入,ID 将起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-13
  • 1970-01-01
  • 1970-01-01
  • 2015-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多