PHP 和 MySQL:按最近日期排序并限制为 10
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7215022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP and MySQL: Order by most recent date and limit 10
提问by James
I am building a notes system on my site and I've got to the stage where users can post notes into the MySQL database using PHP and then PHP prints them out on a page. However, when they print/echo out, the oldest one appears first but I want the most recent first. I also want them to be limited to 10, so only 10 appear on the page. Here is my PHP code, your help will be much appreciated:
我正在我的网站上构建一个笔记系统,我已经到了用户可以使用 PHP 将笔记发布到 MySQL 数据库,然后 PHP 将它们打印在页面上的阶段。但是,当他们打印/回显时,最旧的首先出现,但我想要最新的。我还希望将它们限制为 10 个,因此页面上只显示 10 个。这是我的 PHP 代码,非常感谢您的帮助:
// initialize some variables
$notedisplaylist = "";
$myObject = "";
$result = mysql_query("SELECT * FROM notes WHERE note_author_id='$u_id' ORDER BY date_time");
while($row = mysql_fetch_array($result)){
$note_title = $row["note_title"];
$note_body = $row["note_body"];
$date = $row["date_time"];
$notedisplaylist .= '<h2>' . $note_title . '</h2><br /><p>' . $note_body . '</p><hr /><p>Noted: ' . $date . '</p><hr /><br />';
}
回答by Ackar
This should do it :
这应该这样做:
$result = mysql_query("SELECT * FROM notes WHERE note_author_id='$u_id' ORDER BY date_time DESC LIMIT 0, 10");
回答by Book Of Zeus
use:
用:
SELECT * FROM notes WHERE note_author_id='$u_id' ORDER BY date_time DESC LIMIT 10
DESC : descending order ( from newest to oldest ) LIMIT 10: first 10 records found.
DESC:降序(从最新到最旧) LIMIT 10:找到的前 10 条记录。
回答by gilden
Try
尝试
$result = mysql_query("SELECT * FROM notes WHERE note_author_id='$u_id' ORDER BY date_time DESC LIMIT 10");
For a more detailed explanation on ORDER
and LIMIT
, visit the MySQL doc's articles about sorting rowsand the basic select syntax(look for a bullet describing LIMIT
).
有关更详细的解释ORDER
和LIMIT
信息,请访问MySQL的文档的有关文章排序行和基本选择语法(外观描述子弹LIMIT
)。
回答by mithunsatheesh
give like
给喜欢
ORDER BY date_time DESC
otherwise you are sorting them in ascending order.. thats why older ones come first
否则你是按升序对它们进行排序..这就是为什么老的先到的
回答by dubvfan87
Do this
做这个
$result = mysql_query("SELECT * FROM notes WHERE note_author_id='$u_id' ORDER BY date_time DESC LIMIT 0, 10");
回答by Ali
If in case you want your LIMIT to be a variable, here I named it $limit:
如果你希望你的 LIMIT 是一个变量,我在这里将它命名为 $limit:
"SELECT * FROM tbl ORDER BY input_date DESC LIMIT 0, $limit";