Forum Moderators: coopster

Message Too Old, No Replies

MySQL: Select until count until x=y possible?

         

Karma

11:59 am on Aug 14, 2011 (gmt 0)

10+ Year Member



I'm trying to make the code I use to retrieve visitor comments more efficient. At present, I move all comments for the current 'page name' to an array, and then, depending on the 'page number', select the applicable range and display.

Is there a way to select a range of records from a database without reading them all in first and filtering with PHP?

...My site displays 15 comments per page
...68 comments for the current 'page name'
...visitor is on page 3

1 - 15 = page 1
16 - 30 = page 2
31 - 45 = page 3 <- just get these
46 - 60 = page 4
61 - 68 = page 5

brotherhood of LAN

12:10 pm on Aug 14, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Yes, a fairly regular way of doing it is

1) Get count of all results with COUNT(*) and keep track of that number
2) Use MySQL's LIMIT clause to retrieve the subset of results.

SELECT * FROM table LIMIT 0,15
SELECT * FROM table LIMIT 15,15
SELECT * FROM table LIMIT 30,15
etc

Knowing the overall count also lets you create links to your paginated results.

Karma

3:00 pm on Aug 15, 2011 (gmt 0)

10+ Year Member



I felt like kicking myself when you posted the answer - so damn obvious in hind-sight lol.

Many thanks - working perfectly now :)