[PHP Snippet] Pagination with MySQL

$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;
}