Take the 2-minute tour ×

So I have a database, and I would like to display the last ten entries.

So far I have tried several ways but run into a couple of issues. I have tried using a for-loop starting at the row count for the database and linking that to the ID, but then of course should I delete an entry the iterations will have data missing. For example if I have deleted lots of entries and have the first entry start at id 20 then if there are only 10 rows it will look to display 10 to 1, which don't exist.

Any thoughts?

share|improve this question
use LIMIT and ORDER BY –  Phoenix Jul 21 '12 at 17:08
I little confuse, what do you mean by last ten entries in a database? Normally, is last ten entries in a table. So, are you trying to look for ten tables has just been updated? –  ajreal Jul 21 '12 at 17:14
add comment

2 Answers

You could try, depending on your implementation,

SELECT * FROM `table_name` WHERE conditions ORDER BY `id` DESC LIMIT 10;
share|improve this answer
How would you use this to display the 10 entries? Would you iterate through this? –  mark Jul 21 '12 at 17:10
Assuming you have PHP set to return an array, yes. –  Waleed Khan Jul 21 '12 at 17:11
So, very basic question here, but how would the new for-loop look ideally? –  mark Jul 21 '12 at 17:17
It depends on your database functions. If you're using mysql_*, which you shouldn't be, you'll use while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { // do things with $row }. If you're using PDO, you'll use foreach ($query->result_array() as $row) { // do things with $row }. Dunno about MySQLi. –  Waleed Khan Jul 21 '12 at 17:20
I should be using mysql_*? –  mark Jul 21 '12 at 17:30
show 2 more comments

Try this :

$rs=mysql_query("SELECT id,col1,col2,coln FROM table_name WHERE condt ORDER BY id DESC LIMIT 10") or die(mysql_error());
while($row=  mysql_fetch_row($rs))
share|improve this answer
add comment

Your Answer


