go top

PHP / MySQL select data and split on pages

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. Check our live demo.

We have MySQL table called "students" holding 100 records with the following fields:
ID: autoincrement ID
Name: varchar(250)
PhoneNumber: varchar(250)

Instead of doing a single SELECT query and display all the 100 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.

We will first define MySQL connection variables and connnect to the database

<?php
error_reporting(0);
$servername = "localhost";
$username = "****";
$password = "****";
$dbname = "****";
$datatable = "students"; // MySQL table name
$results_per_page = 20; // number of results per page

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>


Next thing to do is to make a PHP file called index.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) * $results_per_page;
$sql = "SELECT * FROM ".$datatable." ORDER BY ID ASC LIMIT $start_from, ".$results_per_page;
$rs_result = $conn->query($sql);
?>
<table border="1" cellpadding="4">
<tr>
<td bgcolor="#CCCCCC"><strong>ID</strong></td>
<td bgcolor="#CCCCCC"><strong>Name</strong></td><td bgcolor="#CCCCCC"><strong>Phone</strong></td></tr>
<?php
while($row = $rs_result->fetch_assoc()) {
?>
<tr>
<td><? echo $row["ID"]; ?></td>
<td><? echo $row["Name"]; ?></td>
<td><? echo $row["PhoneNumber"]; ?></td>
</tr>
<?php
};
?>
</table>


Now, when you open index.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) * $results_per_page;


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. index.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(ID) AS total FROM ".$datatable; 
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$total_pages = ceil($row["total"] / $results_per_page);


The $total_records is now equal to the number of records that we have in our database, in our case 100. 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 / $results_per_page);


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 100 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='index.php?page=".$i."'>".$i."</a> ";
};
?>


Above code will print numbers from 1 to 5 and for each number will create different link.
index.php?page=1
index.php?page=2
index.php?page=3
index.php?page=4
index.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) * $results_per_page;
$sql = "SELECT * FROM ".$datatable." ORDER BY ID ASC LIMIT $start_from, ".$results_per_page;
$rs_result = $conn->query($sql);
?>
<table border="1" cellpadding="4">
<tr>
<td bgcolor="#CCCCCC"><strong>ID</strong></td>
<td bgcolor="#CCCCCC"><strong>Name</strong></td><td bgcolor="#CCCCCC"><strong>Phone</strong></td></tr>
<?php
while($row = $rs_result->fetch_assoc()) {
?>
<tr>
<td><? echo $row["ID"]; ?></td>
<td><? echo $row["Name"]; ?></td>
<td><? echo $row["PhoneNumber"]; ?></td>
</tr>
<?php
};
?>
</table>

<br />

<?php
$sql = "SELECT COUNT(ID) AS total FROM ".$datatable;
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$total_pages = ceil($row["total"] / $results_per_page); // calculate total pages with results

for ($i=1; $i<=$total_pages; $i++) { // print links for all pages
echo "<a href='index.php?page=".$i."'";
if ($i==$page) echo " class='curPage'";
echo ">".$i."</a> ";
};
?>


This index.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.

If you have any questions you can always use the form below to ask for free help.
Do not forget to check the demo here.

179 Comments to "PHP / MySQL select data and split on pages"

  • karthik

    karthik

    November 29, 2016 at 11:37 am

    how to filter users profile data using php pagination

  • Cris Mark Sotto

    Cris Mark Sotto

    November 15, 2016 at 00:41 am

    GREAT !!!! THANKS :)

  • Jules

    Jules

    November 4, 2016 at 19:16 pm

    Where is the highlight code? please? Thank you!

  • Adam Johnston

    Adam Johnston

    October 12, 2016 at 15:49 pm

    Hi, I would just like to say thank you for this good yet simple and straight to the point guide. That can be difficult to find sometimes! The code worked great for me and it is easy to manipulate to my needs
    I am now trying to create a "next page" link after the page links.

    • Sasho Valkanov

      Sasho Valkanov

      October 12, 2016 at 20:56 pm

      Hi Adam,

      you can use this code to print << and >> for previous and next pages.

      <?php 
      $sql = "SELECT COUNT(ID) AS total FROM ".$datatable;
      $result = $conn->query($sql);
      $row = $result->fetch_assoc();
      $total_pages = ceil($row["total"] / $results_per_page); // calculate total pages with results

      if ($page>1)
      echo "<a href='index.php?page=".($page-1)."'><<</a>";

      for ($i=1; $i<=$total_pages; $i++) { // print links for all pages
      echo "<a href='index.php?page=".$i."'";
      if ($i==$page) echo " class='curPage'";
      echo ">".$i."</a> ";
      };

      if ($page<$total_pages)
      echo "<a href='index.php?page=".($page+1)."'>>></a>";
      ?>

  • Sasho Valkanov

    Sasho Valkanov

    October 4, 2016 at 12:37 pm

    *** UPDATE ***
    We've updated the tutorial:
    - it uses mysqli for database connection
    - number of results per page and MySQL table are set via parameters
    - current page is highlighted
    - working demo is available

  • Abhishek Burkule

    Abhishek Burkule

    June 15, 2016 at 08:27 am

    The First 20 records have been fetch but their os no echo dor next 0age 1,2,3 lik dis at last

  • navitha

    navitha

    October 3, 2015 at 09:25 am

    how to create page

  • navitha

    navitha

    October 3, 2015 at 09:21 am

    i want to display a product details in multiple page how to create like pages.. i cant understand plz help me

  • Shyam

    Shyam

    September 24, 2015 at 15:44 pm

    The below code i have created from the above. Every thing is working fine for me. you can use this.

    <?php
    include 'database.php';
    $db = new DB_Class;
    $conn = $db->conn();
    if (isset($_GET["page"]))
    {
    $page = $_GET["page"];
    }
    else
    {
    $page = 1;
    };
    $start = $page * 15;

    // start and end point
    if($start == 0)
    $start = 1;
    else
    $start =$start+1;

    for($i=0;$i<15;$i++)
    {
    $end_page = $start+$i;
    }
    $start_from = $end_page;

    $sql = "SELECT * FROM
    (
    SELECT
    ROW_NUMBER() OVER( ORDER BY agenda_id ASC ) AS RowNumber,
    program_name, program_hall
    FROM program_details
    ) Q

    WHERE RowNumber BETWEEN $start AND $start_from";
    $rs_result = sqlsrv_query ($conn,$sql);
    ?>
    <table border="01">
    <tr><th>SNO</th><th>Program Name</th><th>Hall</th></tr>
    <?php
    $j = 0;
    while($row = sqlsrv_fetch_array($rs_result,SQLSRV_FETCH_ASSOC))
    {
    $j++;
    ?>
    <tr>
    <td><?php echo $j; ?></td>
    <td><?php echo $row["program_name"]; ?></td>
    <td><?php echo $row["program_hall"]; ?></td>
    </tr>
    <?php
    };
    ?>
    </table>
    <?php
    $query_pag_num = "SELECT COUNT(agenda_id) FROM program_details";
    $result_pag_num = sqlsrv_query($conn,$query_pag_num);
    $row4 = sqlsrv_fetch_array($result_pag_num);
    $count = $row4[0];
    $total_pages = ceil($count / 15);
    for ($i=1; $i<= $total_pages; $i++)
    {
    echo "<a href='index.php?page=".$i."'>".$i."</a> ";
    };
    ?>

  • Craig Nicholson

    Craig Nicholson

    September 22, 2015 at 18:29 pm

    Hi I am totally new to all of this and have had a good crack at this but i can't seem to get the pagination to show on my page.
    as I am new to this i am using Wordpress and have put the code into a page and i get the 15 properties coming back which is ace, but no pagination is showing for pages.

    can you offer any help at all?

    thanks this site is brilliant and maybe out of my league on this one but i would like pagination on my Our Properties page
    this is the link for testing - http://www.luxor-estates.com/test-page-anything/




    such as:


    $servername = ".......";$username = ".....";$password = ".......";$dbname = "..........";
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
    }
    if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
    $start_from = ($page-1) * 15;
    $sql = "SELECT `Property Thumbnail URL`,`Property Title4HTML`,`Image Tag` FROM `Properties`,`Available` WHERE `Property Available Flag` = `Flag` ORDER BY `Property Number` LIMIT $start_from, 15";
    $rs_result = $conn->query($sql);
    echo "<table>
    <tr><td>Property Thumbnail URL</td><td>Property Title4HTML</td><td>Image Tag</td></tr>";
    while($row = $rs_result->fetch_assoc()) {
    echo
    "<tr>
    <td>" . $row['Property Thumbnail URL'] . "</td>
    <td>" . $row['Property Title4HTML'] . "</td>
    <td>" . $row['Image Tag'] . "</td>
    </tr>";
    }
    echo "</table>";
    $sql = "SELECT COUNT(`Property Number`) FROM `Properties`";
    $rs_result = $conn->query($sql);
    $row = $rs_result->fetch_assoc();
    $total_records = $row[0];
    $total_pages = ceil($total_records / 15);

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

Add your comment

Captcha
    • Free Scripts

      Add great new functionalities to your website with our Free Scripts collection.

      Free scripts
    • PHP Scripts

      Check our extensive collection of top-notch PHP Scripts that will enhance your website!

      Commercial PHP scripts