etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

PHP pagination with sortable table on header click

In this article, you will learn how to create PHP pagination with sorting and searching on click the column headers using PHP programming language and MySQL.

Pagination is important when related content on a website has to be divided into several pages in a good layout. If you list all the data on the same page, it will become more confusing and also have more page loading time. Here is a simple PHP pagination example in which we have fetched the data from the MySQL database and written PHP logic to set pagination on the fetched results. All the coding flows are mentioned step by step, which will make it easier to understand and implement.





In addition to the pagination, we have also described a simple process to sort HTML table data in ascending order using PHP and MySQL. Table sorting provides many more benefits to users. They can easily sort the data column wise to analyse the data more effectively. Here is the process of sorting MySQL Table data by column name in ascending order.





Database

In the first step, we have written database connection code. For this, we have created a MySQL table 'user' and inserted data into it as shown below. You can either use your existing database or copy & paste the given code into MySQL-

CREATE TABLE IF NOT EXISTS `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `gender` varchar(10) NOT NULL,
  `city` varchar(80) NOT NULL,
  `email` varchar(100) NOT NULL,
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
INSERT INTO `user` (`id`, `name`, `gender`, `city`, `email`, `timestamp`) VALUES
(1, 'Smith', 'male', 'Pune', This email address is being protected from spambots. You need JavaScript enabled to view it.', '2020-07-26 12:34:11'),
(2, 'Priska', 'Female', 'New Delhi', This email address is being protected from spambots. You need JavaScript enabled to view it.', '2020-07-26 12:34:11'),
(3, 'Arya', 'male', 'Kolkatta', This email address is being protected from spambots. You need JavaScript enabled to view it.', '2020-07-26 12:35:58'),
(4, 'Jorz', 'male', 'Pune', This email address is being protected from spambots. You need JavaScript enabled to view it.', '2020-07-26 12:35:58'),
(5, 'Aryan', 'male', 'Banglore', This email address is being protected from spambots. You need JavaScript enabled to view it.', '2020-07-26 12:37:04'),
(6, 'Lussi', 'female', 'Goa', This email address is being protected from spambots. You need JavaScript enabled to view it.', '2020-07-26 12:37:04');


config.php

Next, we have created a PHP page 'config.php', where we have written database connection code using the PHP programming language. You can either create this manually or copy and paste this code. Only you will have to change the database, hostname, username and password with your database credentials and name.

<?php 
$hostname = "localhost"; 
$username = "root"; 
$password = ""; 
$database= "demo"; 

// Connect to database
$conn = mysqli_connect($hostname, $username, $password, $database);

if (!$conn) {
 die("Connection failed: " . mysqli_connect_error());
} 
?>




index.php

This is the main file that we will call in the browser. This file contains HTML and PHP code to display the records and Next and Previous buttons for pagination. For sorting table data, we have put links in the table header. When you click the table header, the sortorder() method will be called, which contains the column field name as a parameter to sort the table.

<!doctype html>
<html>
<head>
	<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"  crossorigin="anonymous">
    <?php
    include("config.php");

    $row_per_page = 4;
    $row = 0;

    // Previous Button
    if(isset($_POST['prev'])){
        $row = $_POST['row'];
        $row -= $row_per_page;
        if( $row < 0 ){
            $row = 0;
        }
    }

    // Next Button
    if(isset($_POST['next'])){
        $row = $_POST['row'];
        $count = $_POST['count'];

        $val = $row + $row_per_page;
        if( $val < $count ){
            $row = $val;
        }
    }

    // Generate sorting url for table header
    function sortorder($field){
        $sorturl = "?order_by=".$field."&sort=";
        $sorttype = "asc";
        if(isset($_GET['order_by']) && $_GET['order_by'] == $field){
            if(isset($_GET['sort']) && $_GET['sort'] == "asc"){
                $sorttype = "asc";
            }
        }
        $sorturl .= $sorttype;
        return $sorturl;
    }
    ?>
</head>
<body>
<div style="width: 40%; margin: 0 auto; text-align: center;">
    <table class="table table-striped">
        <thead class="table-info">
            <th>Id</th>
            <th><a href="/" class="sort">Name</a></th>
            <th><a href="/" class="sort">Gender</a></th>
            <th><a href="/" class="sort">City</a></th>
            <th><a href="/" class="sort">Email</a></th>
        
        <?php
        // count total number of rows
        $query = "SELECT COUNT(*) AS cntrows FROM user";
        $result = mysqli_query($con,$query);
        $fetchresult = mysqli_fetch_array($result);
        $count = $fetchresult['cntrows'];

        // selecting rows
        $orderby = " ORDER BY id desc ";
        if(isset($_GET['order_by']) && isset($_GET['sort'])){
            $orderby = ' order by '.$_GET['order_by'].' '.$_GET['sort'];
        }
        
        // fetch user data
        $query = "SELECT * FROM user ".$orderby." limit $row,".$row_per_page;
        $result = mysqli_query($con,$query);
        $sno = $row + 1;
        while($fetch = mysqli_fetch_array($result)){
            $name = $fetch['name'];
            $gender = $fetch['gender'];
            $city = $fetch['city'];
            $email = $fetch['email'];
            ?>
            <tr>
                <td align='center'><?php echo $sno; ?></td>
                <td align='center'><?php echo $name; ?></td>
                <td align='center'><?php echo $gender; ?></td>
                <td align='center'><?php echo $city; ?></td>
                <td align='center'><?php echo $email; ?></td>
            </tr>
            <?php
            $sno ++;
        }
        ?>
    </table>
    <form method="post" action="">
            <input type="hidden" name="row" value="<?php echo $row; ?>">
            <input type="hidden" name="count" value="<?php echo $count; ?>">
            <input type="submit" class="btn-primary" name="prev" value="Previous">
            <input type="submit" class="btn-primary" name="next" value="Next">
    </form>
</div>
</body>
</html>

When we execute the above code, the table looks like this-

PHP Sorting Table and Pagination



Related Articles

Ajax live data search using jQuery PHP MySQL
How to encrypt password in PHP
Remove duplicates from array PHP
PHP code to send SMS to mobile from website
How to encrypt password in PHP
PHP remove last character from string
PHP ftp server connection and file handling
PHP code to send email using SMTP
How to lock a file using PHP
How to display PDF file in PHP from database
How to read CSV file in PHP and store in MySQL
Create And Download Word Document in PHP
PHP SplFileObject Standard Library
Simple File Upload Script in PHP
Sending form data to an email using PHP
Recover forgot password using PHP and MySQL
Php file based authentication
Simple PHP File Cache
PHP import Excel data to MySQL using PHPExcel
How to get current directory, filename and code line number in PHP




Most Popular Development Resources
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
PHP Create Word Document from HTML
-----------------
How to get data from XML file in PHP
-----------------
Hypertext Transfer Protocol Overview
-----------------
PHP code to send email using SMTP
-----------------
Characteristics of a Good Computer Program
-----------------
How to encrypt password in PHP
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
How to add multiple custom markers on google map
-----------------
How to get current directory, filename and code line number in PHP
-----------------
Fibonacci Series Program in PHP
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
How to generate QR Code in PHP
-----------------
Simple pagination in PHP
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
PHP MYSQL Advanced Search Feature
-----------------
PHP Server Side Form Validation
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
jQuery File upload progress bar with file size validation
-----------------
Simple PHP File Cache
-----------------
Simple File Upload Script in PHP
-----------------
Php file based authentication
-----------------
To check whether a year is a leap year or not in php
-----------------
Calculate distance between two locations using PHP
-----------------
PHP User Authentication by IP Address
-----------------
PHP Secure User Registration with Login/logout
-----------------
Simple way to send SMTP mail using Node.js
-----------------
How to print specific part of a web page in javascript
-----------------
Simple Show Hide Menu Navigation
-----------------
Detect Mobile Devices in PHP
-----------------
Polling system using PHP, Ajax and MySql
-----------------
PHP Sending HTML form data to an Email
-----------------
Google Street View API Example
-----------------
Get Visitor\'s location and TimeZone
-----------------
SQL Injection Prevention Techniques
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
Convert MySQL to JSON using PHP
-----------------
Set and Get Cookies in PHP
-----------------
CSS Simple Menu Navigation Bar
-----------------
PHP Programming Error Types
-----------------
Date Timestamp Formats in PHP
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
How to add google map on your website and display address on click marker
-----------------
Write a python program to print all even numbers between 1 to 100
-----------------
How to display PDF file in web page from Database in PHP
-----------------
PHP Getting Document of Remote Address
-----------------
File Upload Validation in PHP
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial






Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 3

    Stateful vs Stateless

    A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

  • Dec 29

    Best programming language to learn in 2021

    In this article, we have mentioned the analyzed results of the best programming language for 2021...

  • Dec 20

    How is Python best for mobile app development?

    Python has a set of useful Libraries and Packages that minimize the use of code...

  • July 18

    Learn all about Emoji

    In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

  • Jan 10

    Data Science Recruitment of Freshers

    In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2023. All Rights Reserved.