tags:

views:

480

answers:

4

How can I get the latest entry by the latest DATE field from a MySQL database using PHP?

The rows will not be in order of date, so I can't just take the first or last row.

+6  A: 

You want the ORDER BY clause, and perhaps the LIMIT clause.

$query = 'SELECT * FROM `table` ORDER BY `date` DESC LIMIT 1';
Peter Bailey
+1  A: 
SELECT * FROM [Table] ORDER BY [dateColumn] DESC

If you want only the first row:

In T-SQL:

SELECT TOP(1) * FROM [Table] ORDER BY [dateColumn] DESC

In MySQL:

SELECT * FROM `Table` ORDER BY `dateColumn` DESC LIMIT 1
achinda99
A: 

You can use a combination of the LIMIT and ORDER BY clauses.

For example:

SELECT * FROM entries ORDER BY timestamp DESC LIMIT 1
A: 

You don't have a unique recordid or date revised field you could key in on? I always have at least an auto incrementing numeric field in addition to data created and date revised fields. Are you sure there is nothing you can key in on?

SELECT * FROM table ORDER BY recno DESC LIMIT 1;

or

SELECT * FROM table ORDER BY date_revised DESC LIMIT 1;

So the PHP call would be:

$result = mysql_query("SELECT * FROM table ORDER BY date_revised DESC LIMIT 1");

-- Nicholas

Nicholas Kreidberg