Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP and MySQL: Order by most recent date and limit 10

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 />';
}
like image 423
James Avatar asked Aug 27 '11 14:08

James


People also ask

Does MySQL allow the use of order by and limit in the same query?

In MySQL, the LIMIT clause is used with the SELECT statement to restrict the number of rows in the result set. The Limit Clause accepts one or two arguments that are offset and count. The value of both the parameters can be zero or positive integers.

How do I get the latest date in MySQL?

MySQL LAST_DAY() function MySQL LAST_DAY() returns the last day of the corresponding month for a date or datetime value. If the date or datetime value is invalid, the function returns NULL.

Can we order by date in MySQL?

If you'd like to see the latest date first and the earliest date last, you need to sort in descending order. Use the DESC keyword in this case. ORDER BY exam_date DESC ; Note that in MySQL, NULL s are displayed first when sorting in ascending order and last when sorting in descending order.

How do I arrange in ascending order in MySQL?

The MySQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.


1 Answers

This should do it :

$result = mysql_query("SELECT * FROM notes WHERE note_author_id='$u_id' ORDER BY date_time DESC LIMIT 0, 10");
like image 134
Sylvain Cleymans Avatar answered Oct 16 '22 23:10

Sylvain Cleymans