retrieve most recent row from mysql database

Discussion in 'PHP' started by carl_in_florida, Jul 30, 2007.

  1. #1
    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.
     
    carl_in_florida, Jul 30, 2007 IP
  2. ecentricNick

    ecentricNick Peon

    Messages:
    351
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    0
    #2
    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
     
    ecentricNick, Jul 30, 2007 IP
    carl_in_florida likes this.
  3. krt

    krt Well-Known Member

    Messages:
    829
    Likes Received:
    38
    Best Answers:
    0
    Trophy Points:
    120
    #3
    Remember the LIMIT 1 (no use fetching all rows when you only need one :))
    SELECT * FROM table ORDER BY id DESC LIMIT 1
    Code (markup):
     
    krt, Jul 30, 2007 IP
    carl_in_florida likes this.
  4. carl_in_florida

    carl_in_florida Active Member

    Messages:
    1,066
    Likes Received:
    63
    Best Answers:
    0
    Trophy Points:
    90
    #4
    WOW! Am I noob when it comes to MySQL!

    This took forever.
    I had to use this:
    $rs = $db->Execute( $sql );
    Code (markup):
    So I used

    <?
    $sql = "SELECT * FROM entries ORDER BY id DESC LIMIT 1";
    $rs = $db->Execute( $sql );
    ?>
    Code (markup):
    But then I had to display what I just called so I used this:


    		  <h2><?=$rs->fields['title']?></h2>
    <?=$rs->fields['thumbnail']?>
    Code (markup):

    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
     
    carl_in_florida, Jul 30, 2007 IP