Hi, folks in this article I will show how to write pagination in PHP without page reload using Ajax.
Requirements
- PHP 7.3 and above
- MySQL database
- Database connection using PDO
- Jquery library
Getting started
folder Structure
- css
- js
- config -> dbconnection.php
- index.php
dbconnection.php
$dbhost_name = "localhost";
$database = "pagination"; // your database name
$username = "root"; // Your database username
$password = ""; // Your password//////// Do not Edit below /////////try {
$dbo = new PDO('mysql:host=localhost;dbname='.$database, $username, $password, array(PDO::ATTR_PERSISTENT => true));
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "
";
die();
}
?>
Index.php
<div id="pagination-wrapper" class="results-wrapper">
//loop result of your data
require "config/dbconnection.php";
$total = $dbo->query("SELECT COUNT(id) as rows FROM posts ")
->fetch(PDO::FETCH_OBJ);
$perpage = 3;
$posts = $total->rows;
$pages = ceil($posts / $perpage);
# default
$get_pages = isset($_GET['page']) ? $_GET['page'] : 1;
$data = array(
'options' => array(
'default' => 1,
'min_range' => 1,
'max_range' => $pages
)
);
$number = trim($get_pages);
$number = filter_var($number, FILTER_VALIDATE_INT, $data);
$range = $perpage * ($number - 1);
$prev = $number - 1;
$next = $number + 1;
$stmt = $dbo->prepare("SELECT * FROM posts ORDER BY created_at DESC LIMIT :limit, :perpage");
$stmt->bindParam(':perpage', $perpage, PDO::PARAM_INT);
$stmt->bindParam(':limit', $range, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll();
$dbo = null;
if ($result && count($result) > 0) {
foreach ($result as $key => $row) {
$title = ($row['title']);
$content = ($row['content']);
?>
<div > echo ucfirst($row['title']); ?>div>
}
}
?>
if ($result && count($result) > 0) {
echo "(total pages : $posts ) ";
# first page
if ($number <= 1)
echo " More";
# last page
elseif ($number >= $pages)
echo " Back ";
# in range
else
echo "Back Older ";
}
else {
echo "empty
";
}
?>div>
<script src="js/jquery.js">script>
<script src="js/script.js">script>
Now test your work and also you can download the source code below both the SQL database and js files
Download File 32.8 Kb
35
Continue Reading
davidenabs
Thanks a lot sir!
This tutorial was very helpful
kizinho
You are welcome