Create pagination using php and mysql

This post belongs to newbie php developer. In this post we are going to learn about how to create simple paging program in core php with mysql database.

Paging is very important feature, we always need this feature in our applications.

First of all create your Mysql database and table

CREATE TABLE IF NOT EXISTS `posts` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `title` VARCHAR(200) NOT NULL,
  `description` text NOT NULL,
  `created` datetime NOT NULL,
  `updated` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

So see below code and modify it according to your need. this is a very basic level paging in corephp and mysql.

posts.php


$hostname = 'localhost'; // your mysql hostname
$username = 'root';   // Your mysql db username
$password = 'root';   // You mysql db password
$database = 'demo';       // mysql db name
$con = mysqli_connect($hostname, $username, $password, $database);
 
    if (isset($_GET["page"])) { 
      $page  = $_GET["page"]; 
    } else { 
      $page=1; 
    };
$recordsPerPage=20; 
$start = ($page-1) * $recordsPerPage; 
$query = "SELECT * FROM posts LIMIT $start, $recordsPerPage"; 
$result = mysqli_query($con, $query);
 
echo "";while($row=mysqli_fetch_assoc($result)){echo"";}echo"
TitleDescription
".$row['title']."".$row['description']."
"
;   $query = "SELECT * FROM posts"; $result = mysqli_query($con, $query); //run the query $totalRecords = mysqli_num_rows($result); //count number of records $totalPages = ceil($totalRecords / $recordsPerPage);   echo "".'|<'." "; // Go to 1st page   for ($num=1; $num<=$totalPages; $num++) { echo ".$num."">".$num." "; }; echo "$totalPages">"
.'>|'." "; // Go to last page ?>
Title Description

“;
while ($row = mysqli_fetch_assoc($result)) {
echo “

“.$row[‘title’].” “.$row[‘description’].”

“;
}
echo “”;
$query = “SELECT * FROM posts”;
$result = mysqli_query($con, $query); //run the query
$totalRecords = mysqli_num_rows($result); //count number of records
$totalPages = ceil($totalRecords / $recordsPerPage);
echo ““.’|<‘.” “; // Go to 1st page
for ($num=1; $num<=$totalPages; $num++) {
echo ““.$num.” “;
};
echo ““.’>|’.” “; // Go to last page
?>

Hope this script will help you to create paging in php and mysql

If you like this post please don’t forget to subscribe My Public Notebook for more useful stuff.

Leave a Reply

Your email address will not be published. Required fields are marked *

Top