« 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 | 149 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.

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

poornima August 19, 2014 at 2:06 pm | Reply

0

i have given above code it works fine ...but for each page alignment is taking different width size is not looks good..

pls tel me how to set same table td size for all pages ...
dipali July 31, 2014 at 10:39 am | Reply

0

dear sir,

how to print all records from these pagination code.
It is possible to print one page at time but i dont know how to print all pages at time.

dipali July 31, 2014 at 10:36 am | Reply

0

dear sir,

how can i use pagination while printing records.from these code it is possible to print 1 page at time but how can i print all pages at time.

please help me.
vaidyamanishjoshi July 31, 2014 at 10:38 am

0

Resp Deepalijee,

Can you provide your code ?
dipali July 31, 2014 at 10:26 am | Reply

0

hello sir . this tutorial for pagination is very helpful but please can you tell how to divide pages while printing these 90 records and each page contain maximum 10 records .

please help me.
vaidyamanishjoshi July 31, 2014 at 10:34 am

+2

Simply change

$total_pages = ceil($total_records / 20);

To

$total_pages = ceil($total_records / 10);
dr6yu July 11, 2014 at 10:39 am | Reply

0

Thanks!
muij uddin June 13, 2014 at 2:34 pm | Reply

+2

Nice pagination code. but it shows all the data from database but i want to sql data by id in multiple page..how can i do it please help me.
Niels June 3, 2014 at 2:53 pm | Reply

0

Thanks allot for this post, but I still have problems with it. I'm stuck on having only 1 page, but that's not possible because I have allot more rows then that.

This is my code:



<?php
include('connect-mysql.php');
if (!empty($_GET["page"])) {
$page = $_GET["page"];
} else {
$page=1;
};
$start_from = ($page-1) * 20;
$sqlget = "SELECT *
FROM artikel, images
LIMIT 0, 20
";

$sqldata = mysqli_query($dbcon, $sqlget) or die('error getting');

echo "<table>";
echo "<tr><th>A_ARTCODE</th><th>A_NUMMER</th><th>A_OMSCHRN</th><th>A_REFLEV</th><th>A_WINKEL</th><th>I_ARTCODE</th><th>I_FILE</th></tr>";

while($row = mysqli_fetch_array($sqldata)){
echo "<tr><td align='right'>";
echo $row['A_ARTCODE'];
echo "</td><td align='left'>";
echo $row['A_NUMMER'];
echo "</td><td align='left'>";
echo $row['A_OMSCHRN'];
echo "</td><td align='left'>";
echo $row['A_REFLEV'];
echo "</td><td align='right'>";
echo $row['A_WINKEL'];
echo "</td><td align='right'>";
echo $row['I_ARTCODE'];
echo "</td><td align='right'>";
echo $row['I_FILE'];
//echo "<img src='000000-001000".$row['I_ID']."' />";
echo "</td></tr>";
}

echo "</table>";

$sql = "SELECT COUNT(I_FILE) FROM images";
$rs_result = mysqli_query($dbcon, $sql);
$row = mysqli_fetch_row($rs_result) or die ("mysqli fetch row dies");
$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> ";
//};


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

};
?>


I hope someone can help me.
Andrew May 22, 2014 at 2:15 am | Reply

+3

See here any good solution :)


// START AICI
if (!empty($_GET["page"])) {
$page = $_GET["page"];
} else {
$page=1;
};
$start_from = ($page-1) * 5;
$sql = mysql_query("SELECT * FROM `news_list` ORDER BY `id` DESC LIMIT {$start_from}, 5");
while ($rowm = mysql_fetch_array($sql)) {
$ziua = date('d', $rowm['data']);
$luna = date('M', $rowm['data']);
$cutdesc = (strlen($rowm['description']) > 125) ? substr($rowm['description'],0,120).'...' :$rowm['description'];
echo '<ul class="news-items">
<li>
<div class="news-item-detail">
<a href="#" class="news-item-title">'.$rowm['name'].'</a>
<p class="news-item-preview">'.$cutdesc.'</p>
</div>
<div class="news-item-date">
<span class="news-item-day">'.$ziua.'</span>
<span class="news-item-month">'.$luna.'</span>
</div>
</li>
</ul>';
}

echo '</div> <!-- /widget-content -->
</div> <!-- /widget -->';
$sql = mysql_query("SELECT COUNT(`name`) FROM `news_list`");
$row = mysql_fetch_array($sql);
$total_records = $row[0];
$total_pages = ceil($total_records / 5);

//echo "< ";
//for ($i=1; $i<=$total_pages; $i++) {
// echo "<a href='./news-p".$i.".html'>".$i."</a> ";
//};
echo '<center>';
if($page > 1) {
echo " <a href='./news-p".($page-1).".html' class='btn btn-success'>«PREVIOUS</a> ";
}
for($i=1;$i<=$total_pages;$i++) {
if($i==$page) {
echo "<span class='btn btn-success'>".$i."</span> ";
} else {
echo "<a href='./news-p".$i.".html' class='btn btn-small btn-info'>".$i."</a> ";
}
}
if($page!=$total_pages) {
echo " <a href='./news-p".($page+1).".html' class='btn btn-success'>NEXT»</a> ";
}
echo '</center>';
// END AICI


Have fun!
vaidyamanishjoshi May 16, 2014 at 1:46 pm | Reply

+1

Can Anybody explain How To use Date From Database In pagination Instead of Number like
previous |1 | 2 | 3 | 4 | 5 |..... | Next

E.g. if There is a column lecture_date in mysql database containing dates like 2014-05-16, 2014-05-10, 2014-05-03 etc...Can we Display these Dates in Pagination Instead of Numbers ?
Like : -

Previous | 2014-05-03 | 2014-05-10 | 2014-05-16 | ..... | Next
Muktubek May 16, 2014 at 12:19 pm | Reply

0

Hi every one if you need help about php mysql i can help you this is my skype smtx_muktubek


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 ~