Displaying last x database entries.

Discussion in 'Databases' started by mightyb, Feb 21, 2007.

  1. #1
    What would be the most efficient way to display the last x database entries? For example 5 newest members or 10 latest comments etc. Can somone give or point me to the right bit of sample code?

    Thanks a lot!
     
    mightyb, Feb 21, 2007 IP
  2. voodoo709

    voodoo709 Member

    Messages:
    69
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    48
    #2
    You could do something like

    SELECT * FROM comments WHERE 1 ORDER by id DESC LIMIT 5

    Replace * with the columns you want to retrieve
    Replace WHERE 1 with your own statement if required


    Is this what you where looking for?
     
    voodoo709, Feb 21, 2007 IP
    mightyb likes this.
  3. mightyb

    mightyb Banned

    Messages:
    6,566
    Likes Received:
    405
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Yep thats it! I ended up leaving the wildcard.

    
    <?php
    mysql_connect("localhost", "user", "pass") or die(mysql_error());
    mysql_select_db("dbname") or die(mysql_error());
    
    
    $result = mysql_query("SELECT * FROM links WHERE 1 ORDER by link_id DESC LIMIT 10") 
    or die(mysql_error());  
    
    echo "<table border='1'>";
    echo "<tr> <th>Name</th></tr>";
    
    while($row = mysql_fetch_array( $result )) {
    
    	echo "<tr><td>"; 
    	echo $row['link_content'];
    	echo "</td></tr>"; 
    } 
    
    echo "</table>";
    ?>
    PHP:
    The only problem is that for some reason the 5 limit only returns 3 results and 10 limite returns 7 etc but it should not matter really.

    Thanks!
     
    mightyb, Feb 21, 2007 IP
  4. voodoo709

    voodoo709 Member

    Messages:
    69
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    48
    #4

    That’s strange, have you tried running SELECT * FROM links WHERE 1 ORDER by link_id DESC LIMIT 10 from within phpMyAdmin and see how many rows are being returned ?


    Or do a echo mysql_num_rows($result);
     
    voodoo709, Feb 21, 2007 IP