SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Sep 2001
    Location
    Dublin, Republic of Ireland
    Posts
    20
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Getting the last 5 entries from a table ..

    Hey,

    I have been doing some work for someone, and I was just wondering .. how do I grab the last 5 entries from a table?

    My problem is, lets say the last entry to the table has an ID of 25, that doesn't necessarily that ID number 24 precedes it, ID 24 might have been deleted or whatever, the IDs are in numerical order, going upwards from 1 .. its just that not all the IDs will still be there .. sorry if I explained that wrong.

    So, can anyone help me get the last 5 entries to a table?

    Thanks for any and all help recieved.
    Bob.
    bob@nescience.org | icq:102470667
    www.nescience.org .. are you a nescient?

  2. #2
    epsilon transition cupid's Avatar
    Join Date
    Aug 2001
    Location
    Kent, Ohio
    Posts
    367
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    There should be a far better approach than this, as this makes a redundant query and therefore inefficient. Hopefully someone can find a better solution.

    PHP Code:

    //selecting id only to minimize query cost
    $maxNum mysql_num_rows(mysql_query("select id from tablename"));

    $query mysql_query("select * from tablename limit ".($maxNum 5).", $maxNum");

    while (
    $result mysql_fetch_object($query)) {
        
    //blah
        //blah


  3. #3
    Digital Warrior Renegade's Avatar
    Join Date
    Nov 2000
    Location
    Portland, OR
    Posts
    480
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Try this little snip:

    PHP Code:
    $sql "SELECT * FROM <tablename> ORDER BY id DESC LIMIT 5"
    That SQL statement, will sort the table by id (ORDER BY id), in reverse order (DESC) and limit the returned results to 5 (LIMIT 5)

    Hope that helps
    --There's my 1.5 cents, now where is my change!?!?

  4. #4
    SitePoint Member
    Join Date
    Sep 2001
    Location
    Dublin, Republic of Ireland
    Posts
    20
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks a lot both of you!!
    Bob.
    bob@nescience.org | icq:102470667
    www.nescience.org .. are you a nescient?


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •