Jarf
Jarf

Reputation: 33

Pagination, items per page dependant on number of results (PHP)

long time lurker first time asker.

I'm trying to piece together a pagination function that will take into account the total amount of items and increase the results per page to ensure each page is fully populated.

For example if I had 35 results and I wanted a minimum of 10 results per page it would ideally return 12, 12 & 11 results per page.

Clearly my logic-fu is weak because I for the life of me cannot seem to comprehend this seemingly simple task. Embarrassing (it pains me to ask) as I've been at this for a week now and I know there's a simple answer to this.

I'm not necessarily asking for a solution (though that would be appreciated) as a hint in the right direction may be all I need.

Upvotes: 3

Views: 1475

Answers (2)

Denys Séguret
Denys Séguret

Reputation: 382102

Supposing you have at least 10 items (test it) :

nbPages = floor(nbItems/10)

nbItemsPerPageMax = 10 + ceil((nbItems - 10*nbPages)/nbPages) 

You won't need to adjust for the last page as the limit clause don't need the exact number or items in this case (just use limit numPage*nbItemsPerPageMax, nbItemsPerPageMax).

Upvotes: 2

Yogesh Suthar
Yogesh Suthar

Reputation: 30488

Yo have to write query like this and use LIMIT for limiting how much you wabt to show result out of all result.

select * from table where condition LIMIT 0,12

Upvotes: 0

Related Questions