« Protect email address from spam botsHow to make a PHP calendar »

PHP / MySQL select data and split on pages Posted in PHP Tutorials, MySQL Tutorials | 167 Comments
This tutorial is going to show you how to SELECT data from a MySQL database, split it on multiple pages and display it using page numbers.

We have MySQL table called “students” holding 90 records with the following fields:
Name – varchar(250)
PhoneNumber – varchar(250)
Instead of doing a single SELECT query and display all the 90 records on a single page we can have 5 pages each containing maximum 20 records. To do this we will need to use the LIMIT clause for SELECT command so we can limit the query to show only 20 records. The LIMIT clause also allows you to specify which record to start from. For example this query

$sql = "SELECT * FROM students ORDER BY name ASC LIMIT 0, 20";


returns 20 records sorted by name starting from the first record. This next query

$sql = "SELECT * FROM students ORDER BY name ASC LIMIT 50, 20";


shows 20 records sorted again by name but this time it will start from the 50th record.
So basically in this clause (LIMIT start, count) ‘start’ specify the starting record and ‘count’ specifies how many records to show.

Next thing to do is to make a PHP file called pagination.php which will show the first 20 records from our table. The code below selects and then prints the data in a table.

<?php 
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * 20;
$sql = "SELECT * FROM students ORDER BY name ASC LIMIT $start_from, 20";
$rs_result = mysql_query ($sql, $connection);
?>
<table>
<tr><td>Name</td><td>Phone</td></tr>
<?php
while ($row = mysql_fetch_assoc($rs_result)) {
?>
<tr>
<td><? echo $row["Name"]; ?></td>
<td><? echo $row["PhoneNumber"]; ?></td>
</tr>
<?php
};
?>
</table>


Now, when you open pagination.php in your web browser you will see table showing the first 20 records from your ‘students’ table.

The first 2 lines of the above code

if (isset($_GET["page"])) { $page  = $_GET["page"]; } else { $page=1; }; 
$start_from = ($page-1) * 20;


are used to create a $start_from variable depending on the page that we want to view. Later you will see that we will pass a “page” value using the URL (e.g. pagination.php?page=2) to go to different pages. Next we need to find out the total amount of records in our table and the number of pages that we will need. To do this we run another query using COUNT() function.

$sql = "SELECT COUNT(Name) FROM students"; 
$rs_result = mysql_query($sql,$connection);
$row = mysql_fetch_row($rs_result);
$total_records = $row[0];


The $total_records is now equal to the number of records that we have in our database, in our case 90. We have 20 records per page so the total number of pages that will be needed is 5 (4 pages with 20 records and last page will have 10 records).

Calculating the amount of pages needed using PHP can be done using ceil() function.

$total_pages = ceil($total_records / 20);


We divide the total number of records by records per page and then the ceil() function will round up the result. Now we have 2 new variables - $total_records equal to 90 and $total_pages equal to 5.
To print page numbers and associate URLs to each number we will use for() cycle.

<?php 
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='pagination.php?page=".$i."'>".$i."</a> ";
};
?>


Above code will print numbers from 1 to 5 and for each number will create different link.
pagination.php?page=1
pagination.php?page=2
pagination.php?page=3
pagination.php?page=4
pagination.php?page=5
as you can see each link passes different page value which is used in the SELECT query above.

At the end you should have a file like this (remember to add the MySQL connection string):

<?php 
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * 20;
$sql = "SELECT * FROM students ORDER BY name ASC LIMIT $start_from, 20";
$rs_result = mysql_query ($sql,$connection);
?>
<table>
<tr><td>Name</td><td>Phone</td></tr>
<?php
while ($row = mysql_fetch_assoc($rs_result)) {
?>
<tr>
<td><? echo $row["Name"]; ?></td>
<td><? echo $row["PhoneNumber"]; ?></td>
</tr>
<?php
};
?>
</table>
<?php
$sql = "SELECT COUNT(Name) FROM students";
$rs_result = mysql_query($sql,$connection);
$row = mysql_fetch_row($rs_result);
$total_records = $row[0];
$total_pages = ceil($total_records / 20);

for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='pagination.php?page=".$i."'>".$i."</a> ";
};
?>


This pagination.php file will print a table with maximum 20 records per page and at the bottom 5 page numbers each pointing to a page showing different 20 records.

Do not forget that for a small fee I can add pagination to all your PHP files. Let me know if you need help with this and I will give you a quote.

Do you know PHP / HTML / CSS / JS well?

Write tutorial on a topic you are good in and become a trusted PHP jabber! Share your experience with millions of other webmasters visiting our website. Contact us for more information how to become a contributor.

167 Replies to "PHP / MySQL select data and split on pages"

nilesh dabhi August 11, 2015 at 2:01 pm | Reply

+1

thanks very nice code this is running code..............
hardik August 6, 2015 at 11:52 am | Reply

+2

i have problem with the next button when i come to my last 5 records the loop is going on and on but cant understand here is the code help me
<?php
include ('config.php');
$rec_limit=5;
$sql="SELECT id FROM master";
$result=mysql_query($sql);
$arr=mysql_fetch_array($result);
$rec_count=mysql_num_rows($result);

if(isset($_GET['page']))
{
$page=$_GET['page'] + 1;
$offset=$rec_limit * $page;

}
else
{
$page=0;
$offset=0;
}
$left_rec=$rec_count - ($page * $rec_limit);
?>

<html>
<head>
</head>
<link href="css/style.css" type="text/css" rel="stylesheet" />
<body>

<table align="center" border="1">
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Gender</th>
<th>course</th>
<th>skils</th>
<th>Images</th>
<th>Address</th>
<th colspan="2">Action</th>
</tr>
<?php
$sql="SELECT * FROM master limit $offset,$rec_limit";
$result=mysql_query($sql);

while($arr=mysql_fetch_array($result))
{
?>
<tr>
<td><?php echo $arr['id']; ?></td>
<td><?php echo $arr['fname']; ?></td>
<td><?php echo $arr['lname']; ?></td>
<td><?php echo $arr['gender']; ?></td>
<td><?php echo $arr['course'];?></td>
<td><?php echo $arr['skils']; ?></td>
<td><img src="image/<?php echo $arr['image'];?>" height="50" width="100" /></td>
<td><?php echo $arr['address']; ?></td>


<td><a href="edit.php?id=<?php echo $arr['id'];?>">Edit</a></td>
<td><a href="delete.php?id=<?php echo $arr[ 'id'];?>">delete</a></td>

</tr>

<?php
}
?>
</table>

<div class="pagenation" align="center" >
<div class="wrapper">
<?php
if($page > 0)
{
$end= $page-2;
echo "<a href=\"display.php?page=$end\">PREVIOUS </a> |";
echo "<a href=\"display.php?page=$page\">NEXT</a>";

}
else if($page == 0)
{
echo "<a href=\"display.php?page=$page\">NEXT</a> |";

}
else if($left_rec > $rec_limit)
{

$end = $page-2;
echo "<a href=\"display.php?page=$end\">PRIVIOUS</a> |";
}

?>
</div>
</div>
</body>
</html>
jishan June 29, 2015 at 8:48 am | Reply

0

thanks for detail to me
Sameer Mohammed Quraishi June 20, 2015 at 3:38 pm | Reply

+1

Dear Team,

I would like to Thanks for this tutorial, i need one little help to complete my pagination on Search result page,

This script is working well in index.php, but other page result.php i am getting page number like

123123123123 like this

Please help me to solve this issue,


sushant June 4, 2015 at 9:22 pm | Reply

0

Very helpfull...its overcoming the loading speed issue of datatables in jquery..
Danny May 2, 2015 at 11:46 pm | Reply

+2

Thanks! This was just what I was looking for!
Aminu Muhammad April 18, 2015 at 12:44 pm | Reply

0

I want to collect a data from database and manipulate it by using form and later insert it into different database table. How should i do that please?
Rohit Ranjan March 15, 2015 at 7:21 pm | Reply

+3

There seems to be some error in the last echo statement....
cha March 4, 2015 at 11:51 am | Reply

+2

thanks .. ur so awesome !!
raj mohammed February 16, 2015 at 4:33 pm | Reply

+2

I written all codes but when click page number it will show error like this




Object not found!

The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.

If you think this is a server error, please contact the webmaster.

Error 404

localhost
Apache/2.4.10 (Win32) OpenSSL/1.0.1i PHP/5.6.3




and my coding is





<div id="section">
<?php
include 'admin/connect.php';

if(isset($_GET['page'])) {
$page = $_GET['page'];
}
else {
$page = 3;
};
$start_from = ($page-1) * 3;

$select_post = "SELECT * FROM `posts` order by `post_id` desc LIMIT 0, 3";

$run_posts = mysql_query($select_post);

while($rows=mysql_fetch_array($run_posts)){
$post_id = $rows['post_id'];
$post_title = $rows['post_title'];
$post_date = $rows['post_date'];
$post_auther = $rows['post_auther'];
$post_image = $rows['post_image'];
$post_content = substr($rows['post_content'], 0, 50);

?>
<div class="post">
<h2><?php echo $post_title; ?> </h2>

<p align="left"> Published On: <b> <?php echo $post_date; ?> </b></p>

<center> <img src="images/<?php echo $post_image; ?>" width="160" height="160"> </center>
<div id="spec">
<p align ="justify"> <b>Specifications of item :</b><br> <?php echo $post_content; ?>... <a href="page.php"> Read more</a></p>
</div>
<p align="right"> Published By: <b> <?php echo $post_auther; ?> </b></p>
</div>
<?php }

$sql = "SELECT COUNT(`post_id`) FROM `posts`";
$rs_result = mysql_query($sql, $connect);
$row = mysql_fetch_row($rs_result);
$total_records = $row[0];
$total_pages = ceil($total_records / 3);

for ($i=1; $i<=$total_pages; $i++) {
echo '<a href="content.php?page=".$i."">'.$i.'</a> ';
};
?>
</div>


Please be polite and helpful and do not spam or offend others. We promise you will be treated the same way.

Log in your free account or if you still haven't joined you can create your free account now.

Posting tip:
if you use code in your comments please put it in these tags [php], [sql], [css], [js]
PHP code example: [php] echo date("Y-m-d"); [/php]

Thank you,
~ PHPJabbers team ~