views:

631

answers:

7

I need to display many pages of news in a site.
Should i do the pagination in the db query using limit or do it in my php script after getting all the results?

+8  A: 

Use limit - you don't want to transfer masses of data from the database to the scripting engine if you can avoid it.

David Dorward
A: 

Personally, I would use the query to do it. Obviously, that can change if your dealing with AJAX and such, but just doing a basic limit in the query and outputting the results is simple and efficient.

Scott S.
+6  A: 

Use limit in SQL! Every time!

Otherwise you're throwing around considerably more data than you need to, which makes your scripts unnecessarily slow, and will lead to scalability problems as the amount of data in your tables increases.

Limit is your friend!

Dan
+2  A: 

If you want only work with a DBMS that support this than do it on the DBMS. If you want support other DBMS in the future then ad a layer between that can handle depending on the current DBMS.

Horcrux7
+2  A: 

You can use some existing libraries to help you:

Pear::Pager can help with the output, and to limit the database traffic to only what you need, you can use a wrapper provided in the examples that come with it.

Here's a tutorial I just googled that has it all...

DGM
A: 

Don't do SQL queries manually. Find an MVC framework (I recommend QCodo) that will do the tabular control generation for you - it'll come with inline editing, pagination, Ajax... Everything you'd wish for relational data.

Alex
+1  A: 

In addition to using LIMIT, I'd suggest using an explicit WHERE clause to set the offset, and order the results on that column. For example:

--- First page (showing first 50 records)
SELECT * FROM people ORDER BY id LIMIT 50
--- Second page
SELECT * FROM people WHERE id > 50 ORDER BY id LIMIT 50

This further limits the numbers of rows returned to those within the desired range. Using the WHERE approach (as opposed to a LIMIT clause with a separate offset, e.g. LIMIT 50,50) allows you to deal effectively with paging through records with other natural keys, e.g. alphabetically by name, or by date order.

Rob