I have a submissions table where users can vote on the content. I’d like to add functionality to browse through the submissions in order of votes. I want to limit the number of submissions that appear on each page and implement a pagination system.
So I understand how to use the LIMIT and offset parameters to retrieve rows however this gets the data as it is ordered in the database. I know how to implement pagination in CI. I also know how to ORDER BY the votes column but I’m unsure how to combine the two so that I get the correct output across several pages. Here’s how I’m doing the LIMIT and ORDER BY:
$this->db->limit($count);
$this->db->order_by('votes','desc');
$query = $this->db->get('submission', $num, $offset);
How it should work:
if each page has 10 submissions ordered by votes, the first page should contain the top 10, the second page should contain those submissions with the 11th to the 20th highest votes and so on.
How I’m doing it so far is to simply retrieve all data from the submissions table ordered by votes into an array and then using that as the data source for the pagination. However, this will get rather inefficient as the dataset grows and I would like to know if there is some SQL I’m unaware of that would allow me to only SELECT the appropriate data for each page?
So it looks like I can just construct a query by using ORDER BY followed by the LIMIT and OFFSET for the pagination. I initially tried with a nested select but there’s no need to over-complicate.
Here’s the PHP code using CodeIgniter’s Active Record class:
With this function it’s easy to use CI’s built in pagination functionality:
This does exactly as I wanted without having to get all submissions from the table before sorting.