Skip to content

Instantly share code, notes, and snippets.

@cp6

cp6/page_system.php

Created Jul 3, 2019
Embed
What would you like to do?
Simple PHP MySQL page system
<?php
if (isset($_GET['page'])) {
$page = $_GET['page'];//If ?page= is set use it
} else {
$page = 0;//No ?page= found so we are at page 1 which is a zero
}
$db = new PDO('mysql:host=localhost;dbname=DATABASE;charset=utf8mb4', 'USERNAME', 'PASSWORD');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function pagination_system($page_number, $items_per_page)
{
if ($page_number == 0) {
$start_at = 0;//Items 0 to $items_per_page
} else {
$start_at = ($page_number * $items_per_page);//Assume itemsPP = 4. For Page 2 (1*4) so it shows items 4 to 8
//For Page 3 (?page=2) equation is (2*4) so page=2 will show items 8 to 12
}
global $db;//Call DB connection details
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);//Allows to define a prepared statement for the LIMIT definer
$statement = $db->prepare("SELECT `id`, `color` FROM `objects` ORDER BY `id` DESC LIMIT ?, $items_per_page");//Query
$statement->execute(array($start_at));//Execute query
$row_counter = 0;//Row counter start at 0
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {//Loop through the returned data
echo "[" . $row['id'] . "] " . $row['color'] . "<br>";//Example output for this
$row_counter++;//Adds 1 to row counter
}
$prev_page = $page_number - 1;//Previous page is current - 1
$next_page = $page_number + 1;//next page is current + 1
$is_last_page = 0;//Pre set
if ($row_counter <= ($items_per_page - 1)) {//If less rows returned than itemsPP it is the last page
$is_last_page = 1;
}
if ($page_number == 0) {
if ($row_counter < $items_per_page) {
echo "";//items per page is more than the items we have to paginate = no pagination needed.
} else {//Is first page (0) DONT have a prev button
echo "<a href='?page=$next_page'>[Next]</a>";//Change to Button/icon
}
} elseif ($is_last_page == 1) {//Is last page DONT have a next button
echo "<a href='?page=$prev_page'>[Prev]</a>";//Change to Button/icon
} else {
echo "<a href='?page=$prev_page'>[Prev]</a>";//Change to Button/icon
echo "<a href='?page=$next_page'>[Next]</a>";//Change to Button/icon
}
}
echo pagination_system($page, 4);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.