In this tutorial we will see that how to create Pagination with PHP, PDO using OOP concept, when we have number of records in database then we must Paginate the data, this is very Simple tutorial using PDO and OOP without using Ajax or jQuery it is based on pure PHP, i have created one class file using that class file you can make Pagination of database records and this class file featured with next and previous links based on the page.
now insert some records in the table paste the following code
Create a new file and name it ‘dbconfig.php’ and paste the following code inside it.
Next include the ‘class.paging.php’ file and make an instance of it, pass in the database object to the class to make use of the database.
>> dataview() : function selects the whole records from database table.
>> paging() : function set’s the QueryString like “page_no=number”.
>> paginglink() : function creates the paging number links with “Next and Last” feature.
include above created ‘dbconfig.php’ in this file to use class files functions data.
you can change records per page number in this file i have set 3 .
that’s it we have created here Simple PHP Pagination with PDO using OOP concept.
Feel free to comment your suggestions regarding this tutorial.
Create Database & table
create a database named "dbpaging" and import the following sql code in phpmyadmin.
CREATE TABLE `dbpaging`.`tbl_tutorials` (
`tuts_id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`tuts_title` VARCHAR( 100 ) NOT NULL ,
`tuts_link` VARCHAR( 200 ) NOT NULL
) ENGINE = MYISAM ;
now insert some records in the table paste the following code
INSERT INTO `dbpaging`.`tbl_tutorials` (`tuts_id`, `tuts_title`, `tuts_link`) VALUES (NULL, 'Dynamic Drop Down Menu using PHP & MySQLi', 'https://codingcage.com/2015/03/dynamic-drop-down-menu-using-php-and.html'), (NULL, 'How to use PHP Data Object - PDO tutorial', 'https://codingcage.com/2015/03/how-to-use-php-data-object-pdo-tutorial.html');
INSERT INTO `dbpaging`.`tbl_tutorials` (`tuts_id`, `tuts_title`, `tuts_link`) VALUES (NULL, 'PHP CRUD tutorial with MySQLi extension', 'https://codingcage.com/2015/03/php-crud-tutorial-with-mysqli-extension.html'), (NULL, 'Drop Down Menu using CSS3 & jQuery', 'https://codingcage.com/2015/02/how-to-create-drop-down-menu-using-css3.html');
INSERT INTO `dbpaging`.`tbl_tutorials` (`tuts_id`, `tuts_title`, `tuts_link`) VALUES (NULL, 'Server Side Form Valiations', 'https://codingcage.com/2015/02/server-side-form-validations-using-php.html'), (NULL, 'Registration & Login Script with PHP MySQl', 'https://codingcage.com/2015/01/user-registration-and-login-script-using-php-mysql.html');
INSERT INTO `dbpaging`.`tbl_tutorials` (`tuts_id`, `tuts_title`, `tuts_link`) VALUES (NULL, 'PHP CRUD with MySQL Part - 2', 'https://codingcage.com/2015/01/php-oop-crud-tutorial-with-mysql-part-2.html'), (NULL, 'Delete uploaded files from Folder', 'https://codingcage.com/2014/12/delete-uploaded-files-from-folder-in-php.html');
INSERT INTO `dbpaging`.`tbl_tutorials` (`tuts_id`, `tuts_title`, `tuts_link`) VALUES (NULL, 'Fetch data From Multiple tables', 'https://codingcage.com/2014/12/fetch-data-from-multiple-tables-in-php.html'), (NULL, 'File Upload and View with PHP & MySQl', 'https://codingcage.com/2014/12/file-upload-and-view-with-php-and-mysql.html');
INSERT INTO `dbpaging`.`tbl_tutorials` (`tuts_id`, `tuts_title`, `tuts_link`) VALUES (NULL, 'Simple PHP CRUD operations', 'https://codingcage.com/2014/12/simple-php-crud-operations-with-mysql.html'), (NULL, 'Validations', 'https://codingcage.com/search/label/validations');
INSERT INTO `dbpaging`.`tbl_tutorials` (`tuts_id`, `tuts_title`, `tuts_link`) VALUES (NULL, 'HTML5 Form validations', 'https://codingcage.com/2015/03/html5-form-validations-with-pattern.html'), (NULL, 'PHP', 'https://codingcage.com/search/label/php');
Create a new file and name it ‘dbconfig.php’ and paste the following code inside it.
dbconfig.php
Set the credentials for the database and make a new PDO connection if the connection fails display the error .Next include the ‘class.paging.php’ file and make an instance of it, pass in the database object to the class to make use of the database.
<?php
$db_host = "localhost";
$db_user = "root";
$db_pass = "";
$db_name = "dbpaging";
try
{
$DB_con = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
$DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
echo $exception->getMessage();
}
include_once 'class.paging.php';
$paginate = new paginate($DB_con);
class.paging.php
this is the main class file which paginates the database records.>> dataview() : function selects the whole records from database table.
>> paging() : function set’s the QueryString like “page_no=number”.
>> paginglink() : function creates the paging number links with “Next and Last” feature.
<?php
class paginate
{
private $db;
function __construct($DB_con)
{
$this->db = $DB_con;
}
public function dataview($query)
{
$stmt = $this->db->prepare($query);
$stmt->execute();
if($stmt->rowCount()>0)
{
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<tr>
<td><?php echo $row['tuts_id']; ?></td>
<td><?php echo $row['tuts_title']; ?></td>
<td><a href="<?php echo $row['tuts_link']; ?>">visit</a></td>
</tr>
<?php
}
}
else
{
?>
<tr>
<td>Nothing here...</td>
</tr>
<?php
}
}
public function paging($query,$records_per_page)
{
$starting_position=0;
if(isset($_GET["page_no"]))
{
$starting_position=($_GET["page_no"]-1)*$records_per_page;
}
$query2=$query." limit $starting_position,$records_per_page";
return $query2;
}
public function paginglink($query,$records_per_page)
{
$self = $_SERVER['PHP_SELF'];
$stmt = $this->db->prepare($query);
$stmt->execute();
$total_no_of_records = $stmt->rowCount();
if($total_no_of_records > 0)
{
?><tr><td colspan="3"><?php
$total_no_of_pages=ceil($total_no_of_records/$records_per_page);
$current_page=1;
if(isset($_GET["page_no"]))
{
$current_page=$_GET["page_no"];
}
if($current_page!=1)
{
$previous =$current_page-1;
echo "<a href='".$self."?page_no=1'>First</a> ";
echo "<a href='".$self."?page_no=".$previous."'>Previous</a> ";
}
for($i=1;$i<=$total_no_of_pages;$i++)
{
if($i==$current_page)
{
echo "<strong><a href='".$self."?page_no=".$i."' style='color:red;text-decoration:none'>".$i."</a></strong> ";
}
else
{
echo "<a href='".$self."?page_no=".$i."'>".$i."</a> ";
}
}
if($current_page!=$total_no_of_pages)
{
$next=$current_page+1;
echo "<a href='".$self."?page_no=".$next."'>Next</a> ";
echo "<a href='".$self."?page_no=".$total_no_of_pages."'>Last</a> ";
}
?></td></tr><?php
}
}
}
index.php
this file contains HTML and few lines of PHP code to display Paginated.include above created ‘dbconfig.php’ in this file to use class files functions data.
you can change records per page number in this file i have set 3 .
<?php
include_once("dbconfig.php");
?>
<link rel="stylesheet" href="style.css" type="text/css" />
<table align="center" width="50%" border="1">
<tr>
<td><a href="http://cleartuts.blogspot.com/">PHP Pagination with PDO using OOP concept.</a></td>
</tr>
<tr>
<td>
<table align="center" border="1" width="100%" height="100%" id="data">
<?php
$query = "SELECT * FROM tbl_tutorials";
$records_per_page=3;
$newquery = $paginate->paging($query,$records_per_page);
$paginate->dataview($newquery);
$paginate->paginglink($query,$records_per_page);
?>
</table>
</td>
</tr>
</table>
<div id="footer">
<a href="http://cleartuts.blogspot.com/">cleartuts.blogspot.com</a>
</div>
style.css
@charset "utf-8";
/* CSS Document */
table,td
{
padding:15px;
border-collapse:collapse;
}
#data td
{
padding:10px;
border-collapse:collapse;
position:relative;
font-family:Verdana, Geneva, sans-serif;
}
a
{
text-decoration:none;
color:#00a2d1;
font-family:"Courier New", Courier, monospace;
font-weight:bold;
font-family:Tahoma, Geneva, sans-serif;
}
#footer
{
text-align:center;
margin-top:50px;
}
that’s it we have created here Simple PHP Pagination with PDO using OOP concept.
Feel free to comment your suggestions regarding this tutorial.
thanks man...
ReplyDeletei was looking for the same...
Great tutorial? Is there any chance that there is a method to implementing a text search feature? thank you!
ReplyDeleteI'm a bit of a newbie..any instruction on how to implement the select query?
ReplyDeleteDid you get any reply on this?
DeleteCan you help on how to include variables in the query SELECT
ReplyDeleteI will send these variables from another script
I have tried but it didn't work. Please help.
Thank you
you have to use $_POST[] or $_GET[] variable
DeleteSELECT * FROM tbl_user WHERE user_id='$_GET[var_name]'
No. It only displays the first page. After that displays the Nothing here... message.
DeleteThanks for the tip any way... Can you suggest something else?
Thanks for the Script..
ReplyDeleteThanks. I have one question, how can I get the table data to display in descending order (as opposed to ascending). I'm trying to get the newest entries from my database to show up first rather than the old entries.
ReplyDeleteHi Pradeep, I figured out the answer to my question. In the index file I made this change at line 14:
ReplyDelete$query = "SELECT * FROM tbl_tutorials";
to
$query = "SELECT * FROM tbl_tutorials ORDER BY [please insert a column name here!] DESC";
Nice blog...Very useful information is providing by ur blog. Great beginning php tutorials Very clear and helpful for beginners.
ReplyDeletePradeep, I need some help please. I'm trying to use your scrip for upload & view tutorial, and this tutorial problem is I'm not getting it right. I encounter various errors, or data doesn't get uploaded to the database. Can you please do a tutorial that uses both of these tutorials.
ReplyDeleteOk , I'll make a tutorial about it, soon...
DeleteThank you, great tutorial, worked perfectly.
ReplyDeleteyou're welcome marcos :)
DeleteHi..unable to download script
ReplyDeletePlease help.
Great script, very useful, many thanks. If i could ask though, I'm looking try and limit the displayed pagination to 5, and have them scroll on clicking next/back. As opposed to showing all page numbers at once. Don't suppose you have any pointers? Thanks again.
ReplyDeleteyes you can give limit to 5 for display pages with 5 records just replace 3 with 5 in "$records_per_page=3"; variable.
DeleteAppreciate your quick reply, if I'm not mistaken that would vary the number of results shown on each page? What I'm attempting (and currently failing!!) to do is limit the page numbers being displayed at any given time. So if i have enough results to create 15 pages, only 5 page links would be displayed. Thanks.
Deletethis is what exactly i'd like to ask too. upvote
Deleteupvote. hundreds of page numbers... :/
Deletecan we limit before 3 and after tree page number and other ...
First - Previous - ... - 7 - 8 - 9 - 10 - 11 - 12 - 13 - ... - Next - Last
http://www.ubilisim.com/dosyalar/ice_screenshot_20161128-101100.png
Delete:/
Not so good.
This comment has been removed by the author.
ReplyDeleteHi, great script, I have one question.
ReplyDeletewhen I linked with my customer database, it shows so many numbers with the pagination.
can you modify that to get like this :
1 2 3 .....7 8 9 Next > Last >>
Like put some dots to pagination?
Thanks!
tanx for this tutorial, bt i can i get script to paginate dynamicallly generated page
ReplyDeleteAwesome and Elegant script i was looking for thanks a lot... What if i want to align pagination to center of table how to achieve it..?
ReplyDeleteerror on page in dbcongig.
ReplyDeleteit shows
warning: include_once(class.paging.php): failed to open stream: No such file or directory in F:\cse\training\php\wamp64\www\suffi\pagination\dbconfig.php on line 18
very easy i dont understand nothing
ReplyDeleteAwesome!!!
ReplyDeletei have error
ReplyDeleteFatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '3,3' at line 1 in /opt/lampp/htdocs/Apgredz/class/class_paging.php:9 Stack trace: #0 /opt/lampp/htdocs/Apgredz/class/class_paging.php(9): PDOStatement->execute() #1 /opt/lampp/htdocs/Apgredz/pagination.php(17): paginate->dataView('SELECT * FROM p...') #2 {main} thrown in /opt/lampp/htdocs/Apgredz/class/class_paging.php on line 9
hello sir. plsss add a script search with pagination...
ReplyDeletethank you dear friend
ReplyDeleteMy problem was resolved
Box.com link not working. can you upload again.
ReplyDeleteTHANKS AM USING THIS SCRIPT FOR A PROJECT. (I EDITED IT ).
ReplyDeleteWhy do you use HTML and echo's in your functions?
ReplyDeleteThanks! Amazing code. I using with search field in my project.
ReplyDelete