Bennett Hollstein

Web developer

[PHP Snippet] Simple Paging Script with MySQL and PHP

Hello,

here is a simple script to enable Paging with a MySQL Database:

$command = "SELECT * FROM `posts` ORDER BY added DESC"; // You can change, generate this however you want
$perPage = 20; // Entries per page
if (isset($_GET["page"]) && $_GET["page"] !== 0) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $perPage;
$num = mysqli_query($db, $command); // $db is your mysqli connection to the Database
$total_results = mysqli_num_rows($num);
$command .= " LIMIT $start_from, $perPage";
$exe = mysqli_query($db, $command); // Second MySQL query
if (($total_results - ($num_rec_per_page * $page)) > 0) {
 $nextPage = $page + 1;
}

if ($page > 1) {
 $lastPage = $page - 1;
}


// You can now use while($row = mysqli_fetch_assoc($exe)) to get all entries for the current page.

// This checks, if the current page is the last page or if there is another page
if (($total_results - ($num_rec_per_page * $page)) > 0) {
 $nextPage = $page + 1;
}
// This checks, if there is a previous page
if ($page > 1) {
 $lastPage = $page - 1;
}

Thats it.

You can now show and hide the last page and next page buttons like this:

<?php
if (isset($lastPage)) {
 ?>

 <div class="pull-left"><a href="?page=<?= $lastPage; ?>" class="btn btn-primary btn-raised">Previous Page</a></div>

 <?php
 }
 if (isset($nextPage)) {
 ?>

 <div class="pull-right"><a href="?page=<?= $nextPage; ?>" class="btn btn-primary btn-raised">Next Page</a></div>

 <?php
 }
?>

 

Kommentar verfassen