« 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 | 136 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 knowledge with thousands of webmasters and we will reward you for your generosity by giving you bonus points which you can use as a voucher to buy any of our commercial products. Read more about our reward program.

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

raja March 29, 2014 at 10:45 am | Reply

0

I have this error when i try to execute this code
Warning: mysqli_fetch_row() expects parameter 1 to be mysqli_result, boolean given in C:xampphtdocspgs.php on line 32

code:
<?php

$con=mysqli_connect("localhost","root","","phantomfx"); // include your code to connect to DB.
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * 5;
//$sql = "SELECT * FROM assign ORDER BY id ASC LIMIT $start_from, 5";
$rs_result = mysqli_query ($con,"SELECT * FROM assign ORDER BY id ASC LIMIT $start_from, 5");

echo "<table>
<tr>
<td>Name</td>
<td>Project</td>

</tr>";

while ($row = mysqli_fetch_assoc($rs_result)) {

echo "<tr>";
echo "<td>".$row['username']."</td>";
echo "<td>".$row['shot']."</td>";
echo "</tr>";

}
echo "</table>";
//$sql = "SELECT COUNT(userame) FROM assign";
$result = mysqli_query($con,"SELECT COUNT(userame) FROM assign");
$row = mysqli_fetch_row($result);
$total_records = $row[0];
$total_pages = ceil($total_records / 5);

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

};

?>
Praveen March 24, 2014 at 11:39 am | Reply

+1

Sir is there is any way to use the created page in format 'previous page' '1' '2' '3' ......'250' 'last page' 'next page'
amin March 19, 2014 at 4:09 pm | Reply

0

hi
tnx for your toturial
there is a bug in

if (isset($_GET["page"]))
the correct code is :
if (!empty($_GET["page"]))

because url could be "mysite/pagination.php?page="
and now isset return true and an error occur but using !empty return false and that is what we want

best reguards
dr Manish joshi March 13, 2014 at 9:44 am | Reply

+1

Thanx for nice code.

One problem i am facing...

when page is loaded , it is showing records like 1 2 3 4 5
(i.e. on lec-history.php)
When i click on 2, in address bar, it is showing as lec_history.php?page=2

But showing records like 1 2 3 4 5 for navigation is not seen.
Pierre February 7, 2014 at 11:29 pm | Reply

+3

Many thanks for the tutorial. Very simple to apply and works perfectly.
Reality January 15, 2014 at 2:25 am | Reply

+2

I recommend to not use this code. Although I was very happy with it at first, it keeps not showing the first results. If I have a list like this:

1. Bob
2. Rick
3. Ron

It will give me as a result:

Rick
Ron

This is not a good thing for your website.
Cody February 9, 2014 at 11:41 am

+2

Make sure you are including the
$start_from = ($page-1) * 20; 

line.

That formula should always start at record 0, rather than record 1. (remember arrays begin with zero).
ilavenil December 24, 2013 at 2:21 am | Reply

+1

This code works like a champ!!!Very well explained...well done Sunil....
Sunil Kumar February 9, 2014 at 12:48 pm

+2

Thank you, ilavenil
dulichand kumawat panchota nawa city December 13, 2013 at 12:52 pm | Reply

+3

i am also very happy about this program
sakil_suva November 13, 2013 at 2:42 am | Reply

+2

Nice post. Thanks a lot
@Sunil thanks for your help.
haseeb October 23, 2013 at 2:33 am | Reply

+1

what is the purpose of ? in "<a href='pagination.php?page=".$i."'>".$i."</a> ";
plzzz tell me
sunil October 23, 2013 at 7:24 am

+2

it was the page link which you want to display the data upto ten.... without that link the pagination will not work so that the page numbers will be display in the place of that code in the HTML page....


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 our Webmaster Community Reward Program, 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 ~