Last active
December 20, 2015 17:59
-
-
Save jamesduncombe/6172924 to your computer and use it in GitHub Desktop.
Pagination with MySQL and PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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