View Full Version : retrieve most recent row from mysql database
carl_in_florida
Jul 30th 2007, 6:43 am
Can someone point me to a tutorial that will show me how to display the most recent row from a mysql database table?
I already have a page that paginates results from a table, but I would like to display the most recent entry from each table on the front page of my site.
Thanks
edit: I have an ascending field "id" that is the primary key.
ecentricNick
Jul 30th 2007, 6:52 am
That depends on the structure of your table. If you have an autoincrement ID, which for the sake of argument we'll assume you called "Id" then...
Select * from <table> where <blah blah blah> order by Id DESC
Or, perhaps you have a timestamp column when the record was created...
Select * from <table> where <blah blah blah> order by TimeStamp DESC
But you get the idea.... ORDER BY <column> DESC
krt
Jul 30th 2007, 7:11 am
Remember the LIMIT 1 (no use fetching all rows when you only need one :))
SELECT * FROM table ORDER BY id DESC LIMIT 1
carl_in_florida
Jul 30th 2007, 7:30 am
WOW! Am I noob when it comes to MySQL!
This took forever.
I had to use this:
$rs = $db->Execute( $sql );
So I used
<?
$sql = "SELECT * FROM entries ORDER BY id DESC LIMIT 1";
$rs = $db->Execute( $sql );
?>
But then I had to display what I just called so I used this:
<h2><?=$rs->fields['title']?></h2>
<?=$rs->fields['thumbnail']?>
I know this is elementary stuff but it took me all morning to figure out. I am posting this so anyone in the future who searches for it will have a comprehensive answer.
+green for everyone who replied
Thanks
vBulletin® v3.8.4, Copyright ©2000-2009, Jelsoft Enterprises Ltd.