Created
September 3, 2018 18:02
-
-
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
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 | |
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