[thelist] getting last entry from a table (mysql)

Paul Waring paul at xk7.net
Thu Oct 20 03:37:38 CDT 2005


On Thu, Oct 20, 2005 at 04:08:47PM +0800, Alex Beston wrote:
> im trying to access the most recent row of a table.
> 
> ive used   mysql_insert_id() to get the id of an insert just performed, 
> but this one is to find the one with the largest id, which could have 
> been added any time in the past.

You definitely just want the row with the largest ID? If so you just
want to use the LIMIT keyword like so:

$result = mysql_query("SELECT * FROM my_table ORDER BY id DESC LIMIT
1");
$row = mysql_fetch_row($result);

LIMIT X means "fetch the first X rows from this query", so you'll only
get one row returned. I'm not sure if it's more efficient on the MySQL
side of things but it should mean you get a smaller result set and I
would hope that MySQL is optimised in some way such that asking the
database to return the top result only is more efficient than returning
all the rows and selecting the top one in PHP.

Hope this helps.

Paul

-- 
Rogue Tory
http://www.roguetory.org.uk



More information about the thelist mailing list