Skip to content

Instantly share code, notes, and snippets.

@thepsion5
Created September 3, 2018 18:02
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 thepsion5/0791f4d61cc90f8b8d632d0af7512c5a to your computer and use it in GitHub Desktop.
Save thepsion5/0791f4d61cc90f8b8d632d0af7512c5a to your computer and use it in GitHub Desktop.
A simple example of procedural PHP code that can be used to generated paginated results from a database query
<?php
require 'setup/connection.php'; //returns a PDO instance;
$searchTerm = isset($_GET['search']) ? $_GET['search'] : null;
$currentPage = isset($_GET['page']) ? $_GET['page'] : 1;
//Step 1: Get the total number of results for a search
$sqlParams = [];
$totalResultSql = 'SELECT COUNT(*) AS count FROM articles ';
if ($searchTerm) {
$sqlParams['search'] = "%$searchTerm%";
$totalResults .= 'WHERE description LIKE :search OR title LIKE :search';
}
$totalResultsStatement = $pdo->prepare($totalResultsSql);
$totalResultsStatement->execute($sqlParams);
$totalResults = $totalResultsStatement->fetchAll()[0]['count'];
$totalPages = ceil($totalResults / 10);
//Step 2: Get the actual results for a particular page
$offset = ($currentPage - 1) * 10;
$pagedResultsSql = 'SELECT * FROM articles ';
if ($searchTerm) {
$pagedResultsSql .= 'WHERE description LIKE :search OR title LIKE :search';
}
$pagedResultsSql = "OFFSET $offset LIMIT 10';
$resultStatement = $pdo->prepare($pagedResultsSql);
$resultStatement->execute();
$paginatedResults = $resultStatement->fetchAll();
//Step 3 - display the current page and links to previous and next pages, if applicable
echo "<p>Found $totalResults Results. Showing page $currentPage of $totalPages</p>";
if($currentPage < $totalPages) {
echo "<a href='?search=$search&page=" . ($currentPage + 1) . "'>Next Page</a>";
}
if($currentPage > 1) {
echo "<a href='?search=$search&page=" . ($currentPage - 1) . "'>Previous Page</a>";
}
//Step 4 - display the current page of resuls
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment