Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort by date (newest)

Tags:

php

mysql

Right now I'm sorting by each articles auto_increment id with the query below

mysql_query("SELECT * FROM articles ORDER BY id DESC");

I want to know how to sort by a date field I made, that stores the current date via, strtotime() it should query the dates from newest to oldest.

Current code

$alist = mysql_query("SELECT * FROM articles ORDER BY id DESC");
$results = mysql_num_rows($alist);
    
if ($results > 0){
while($info = mysql_fetch_array($alist)) {
  // query stuff 
  echo $info['time'];
}
like image 494
kr1zmo Avatar asked Jul 31 '10 01:07

kr1zmo


People also ask

How do you sort dates from oldest to newest?

Click Home tab > arrow under Sort & Filter, and then click Sort Oldest to Newest, or Sort Newest to Oldest.

What is sort by newest?

It brings your latest products to the top of the linstings in category, manufacturer, search and special pages. This way your loyal visitors can easily see what's new in your store which is also a good sales driving tehnique.

Why is Excel not filtering dates correctly?

Reason 1: Grouping dates in filters is disabled In Excel, go to File. Click on Options (usually in the left bottom corner of the screen). Go to the Advanced tab in the left pane of the Options window). Scroll down to the workbook settings and set the check at “Group dates in the AutoFilter menu”.


2 Answers

Just change the column in the ORDER BY:

SELECT * FROM articles ORDER BY time DESC
like image 198
Mark Byers Avatar answered Sep 28 '22 19:09

Mark Byers


Let MySQL handle the date stuff - IMO its MUCH better at it than PHP...

add a column with DATE or DATETIME type in your table. On inserting a new record either use NOW() or set a trigger to do it for you (will have to allow null in the coulmn if you are going to user a trigger)

your query should be:

$alist = mysql_query("SELECT * FROM articles ORDER BY `your_date_field` DESC");
like image 37
Ian Wood Avatar answered Sep 28 '22 20:09

Ian Wood