Created
July 23, 2017 16:49
-
-
Save elraghifary/6fc976398ee01ba9332d7b87c1375b3f to your computer and use it in GitHub Desktop.
Paginate data from MySQL in reverse order
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 | |
// database connection | |
$dbHost = 'localhost'; | |
$dbUsername = 'root'; | |
$dbPassword = 'secret'; | |
$dbName = 'database_name'; | |
$conn = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); | |
if ($conn->connect_error) { | |
die("Connection failed: " . $conn->connect_error); | |
} | |
// how many records should be displayed on a page? | |
$records_per_page = 10; | |
// include the pagination class | |
require 'path/to/Zebra_Pagination.php'; | |
// instantiate the pagination object | |
$pagination = new Zebra_Pagination(); | |
// show records in reverse order | |
$pagination->reverse(true); | |
// when showing records in reverse order, we need to know the total number | |
// of records from the beginning | |
$count = mysqli_query($conn, 'SELECT COUNT(id) AS records FROM countries') or die (mysqli_error($conn)); | |
// pass the total number of records to the pagination class | |
$total = mysqli_fetch_assoc($count); | |
$pagination->records(array_pop($total)); | |
// records per page | |
$pagination->records_per_page($records_per_page); | |
// the MySQL statement to fetch the rows | |
// note the LIMIT - use it exactly like that! | |
// also note that we're ordering data descendingly - most important when we're | |
// showing records in reverse order! | |
$sql = ' | |
SELECT | |
country | |
FROM | |
countries | |
ORDER BY | |
country DESC | |
LIMIT | |
' . (($pagination->get_pages() - $pagination->get_page()) * $records_per_page) . ', ' . $records_per_page . ' | |
'; | |
// run the query | |
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn)); | |
?> | |
<table> | |
<tr><th>Country</th></tr> | |
<?php $index = 0; while ($row = mysqli_fetch_assoc($result)): ?> | |
<tr<?php echo $index++ % 2 ? ' class="even"' : ''; ?>> | |
<td><?php echo $row['country']; ?></td> | |
</tr> | |
<?php endwhile; ?> | |
</table> | |
<?php | |
// render the pagination links | |
$pagination->render(); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment