PHP/MySQL retrieval

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mjseaden
Forum Contributor
Posts: 458
Joined: Wed Mar 17, 2004 5:49 am

PHP/MySQL retrieval

Post by mjseaden »

Hi

Can you tell me how I retrieve the last two rows from a database table? Is this possible using a query? Currently I use an overly long-winded PHP method of doing it.

Many thanks

Mark
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

Define "last two rows" of a table. Because rows have no order per definition in a table.

If you select them, you can apply an order on them by using the ORDER clause. Witch the ASC | DESC you can change invert them.

Most DBMS support a method to restrict the number of returned rows in a resultset. For example: MySQL and PostgreSQL have LIMIT, MSSQL has TOP.
User avatar
harrisonad
Forum Contributor
Posts: 288
Joined: Fri Oct 15, 2004 4:58 am
Location: Philippines
Contact:

Post by harrisonad »

if your table has an auto_increment field, you can retrieve that last two rows by ordering them descendingly and limiting the output to 2

Code: Select all

SELECT * FROM table_name ORDER BY id DESC LIMIT 2
Post Reply