PHP and MySQL: Order by most recent date and limit 10
Asked Answered
C

6

16

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 />';
}
Concenter answered 27/8, 2011 at 14:3 Comment(0)
P
30

This should do it :

$result = mysql_query("SELECT * FROM notes WHERE note_author_id='$u_id' ORDER BY date_time DESC LIMIT 0, 10");
Paregoric answered 27/8, 2011 at 14:6 Comment(0)
N
10

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.

Nonanonage answered 27/8, 2011 at 14:6 Comment(0)
B
7

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 rows and the basic select syntax (look for a bullet describing LIMIT).

Berriman answered 27/8, 2011 at 14:6 Comment(0)
C
6

give like

 ORDER BY date_time DESC

otherwise you are sorting them in ascending order.. thats why older ones come first

Cumbrous answered 27/8, 2011 at 14:6 Comment(0)
T
5

Do this

$result = mysql_query("SELECT * FROM notes WHERE note_author_id='$u_id' ORDER BY date_time DESC LIMIT 0, 10");
Theodicy answered 27/8, 2011 at 16:21 Comment(0)
O
0

If in case you want your LIMIT to be a variable, here I named it $limit:

"SELECT * FROM tbl ORDER BY input_date DESC LIMIT 0, $limit";
Orpah answered 15/1, 2017 at 1:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.