Skip to content

Instantly share code, notes, and snippets.

@jamesduncombe
Last active December 20, 2015 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesduncombe/6172924 to your computer and use it in GitHub Desktop.
Save jamesduncombe/6172924 to your computer and use it in GitHub Desktop.
Pagination with MySQL and PHP
<?php
/**
* Handling offsets for articles in series using PHP and MySQL
* pages is the table for articles
*/
$number_of_articles_per_page = 10;
$page = 1;
$page_offset = ($page - 1) * $number_of_articles_per_page;
// Query to get count of number of series in list of articles
$number_of_series = "SELECT COUNT(*) FROM (SELECT * FROM pages ORDER BY id LIMIT ".$page_offset.",".$number_of_articles_per_page.") as a where number_in_series = 1";
// Query to get all articles limited to the correct number per page
$articles = "SELECT * FROM pages WHERE series IN
(SELECT series FROM
(SELECT * FROM pages ORDER BY id LIMIT ".$page_offset.",".$number_of_articles_per_page.")
AS a WHERE number_in_series = 1)
OR id IN
(SELECT id FROM (SELECT * FROM pages WHERE series = '' ORDER BY id LIMIT ".$page_offset.",".$number_of_articles_per_page.") as other_batch)";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment