PHP 和 MySQL:按最近日期排序并限制 10
我正在我的网站上构建一个注释系统,并且已经到了用户可以使用 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 />';
}
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:
// 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 />';
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这应该可以做到:
This should do it :
使用:
DESC :降序(从最新到最旧)
LIMIT 10:找到的前 10 条记录。
use:
DESC : descending order ( from newest to oldest )
LIMIT 10: first 10 records found.
尝试
有关
ORDER
和LIMIT
的更详细说明,请访问 MySQL 文档中关于 对行进行排序 和基本的 选择语法(查找描述LIMIT
的项目符号)。Try
For a more detailed explanation on
ORDER
andLIMIT
, visit the MySQL doc's articles about sorting rows and the basic select syntax (look for a bullet describingLIMIT
).否则
你将按升序对它们进行排序..这就是为什么较旧的排在第一位的原因
give like
otherwise you are sorting them in ascending order.. thats why older ones come first
这样做
Do this
如果您希望 LIMIT 是一个变量,这里我将其命名为 $limit:
If in case you want your LIMIT to be a variable, here I named it $limit: