Datatable AJAX pagination with PHP and PDO

With Datatable you can easily implement pagination on the webpage in less time.

It gives all necessary features which require in the pagination like – searching, sorting, change the number of records display.

You only need to manage the AJAX file.

In this tutorial, I show how you can add Datatable pagination with PHP and PDO.

Datatable AJAX pagination with PHP and PDO


  1. Table structure
  2. Configuration
  3. Download & Include
  4. HTML
  5. Script
  6. PHP
  7. Demo
  8. Conclusion

1. Table structure

Create employee table.

CREATE TABLE `employee` (
  `emp_name` varchar(80) NOT NULL, 
  `salary` varchar(20) NOT NULL,
  `gender` varchar(10) NOT NULL,
  `city` varchar(80) NOT NULL,
  `email` varchar(80) NOT NULL

2. Configuration

Create a config.php for a database connection.

Completed Code

$server = "localhost";
$username = "root";
$password = "";
$dbname = "tutorial";

// Create connection
   $conn = new PDO("mysql:host=$server;dbname=$dbname","$username","$password");
}catch(PDOException $e){
   die('Unable to connect with the database');

3. Download & Include

  • Download Datatables from here.
  • Include datatables.min.css and datatables.min.js in <head> section and also include jQuery Library.
  • You can also use CDN.
<!-- Datatable CSS -->
<link href='//' rel='stylesheet' type='text/css'>

<!-- jQuery Library -->
<script src=""></script>

<!-- Datatable JS -->
<script src="//"></script>


Create a <table id='empTable' class='display dataTable'> and add column name in <thead>.

Completed Code

<!-- Datatable CSS -->
<link href='//' rel='stylesheet' type='text/css'>

<!-- jQuery Library -->
<script src=""></script>

<!-- Datatable JS -->
<script src="//"></script>

<!-- Table -->
<table id='empTable' class='display dataTable'>

      <th>Employee name</th>


5. Script

Initialize DataTable on <table id='empTable'>.

Enable serverside processing and set POST method using options. Send AJAX request to 'ajaxfile.php'.

In the columns option pass field names which gets read when AJAX successfully callback.

Completed Code

      'processing': true,
      'serverSide': true,
      'serverMethod': 'post',
      'ajax': {
      'columns': [
         { data: 'emp_name' },
         { data: 'email' },
         { data: 'gender' },
         { data: 'salary' },
         { data: 'city' },

6. PHP

Create a new ajaxfile.php file.

Read Datatable POST values.

Setup a search query if $searchValue is not empty.

Count total records with and without search filter.

Fetch all records from employee table and initialize $data Array with values.

Return $response Array in JSON format.

Completed Code

include 'config.php';

## Read value
$draw = $_POST['draw'];
$row = $_POST['start'];
$rowperpage = $_POST['length']; // Rows display per page
$columnIndex = $_POST['order'][0]['column']; // Column index
$columnName = $_POST['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
$searchValue = $_POST['search']['value']; // Search value

$searchArray = array();

## Search 
$searchQuery = " ";
if($searchValue != ''){
   $searchQuery = " AND (emp_name LIKE :emp_name or 
        email LIKE :email OR 
        city LIKE :city ) ";
   $searchArray = array( 

## Total number of records without filtering
$stmt = $conn->prepare("SELECT COUNT(*) AS allcount FROM employee ");
$records = $stmt->fetch();
$totalRecords = $records['allcount'];

## Total number of records with filtering
$stmt = $conn->prepare("SELECT COUNT(*) AS allcount FROM employee WHERE 1 ".$searchQuery);
$records = $stmt->fetch();
$totalRecordwithFilter = $records['allcount'];

## Fetch records
$stmt = $conn->prepare("SELECT * FROM employee WHERE 1 ".$searchQuery." ORDER BY ".$columnName." ".$columnSortOrder." LIMIT :limit,:offset");

// Bind values
foreach($searchArray as $key=>$search){
   $stmt->bindValue(':'.$key, $search,PDO::PARAM_STR);

$stmt->bindValue(':limit', (int)$row, PDO::PARAM_INT);
$stmt->bindValue(':offset', (int)$rowperpage, PDO::PARAM_INT);
$empRecords = $stmt->fetchAll();

$data = array();

foreach($empRecords as $row){
   $data[] = array(

## Response
$response = array(
   "draw" => intval($draw),
   "iTotalRecords" => $totalRecords,
   "iTotalDisplayRecords" => $totalRecordwithFilter,
   "aaData" => $data

echo json_encode($response);

7. Demo

8. Conclusion

Return Array data key name must be same as specified in columns option while Datatable initializing.

You can also view without PDO version here.

If you found this tutorial helpful then don't forget to share.
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request.
Spread the love
  • 3


  1. François Beerten said:

    Have adjusted your example to my data file with 750 records.
    however, if I want to go to the next page via ‘next’, I sometimes get an error message on some pages! I can see page 1,4,5,6,7,8,10, but on page 2,3,9 I get the error message below.
    DataTables warning: table id=empTable – Invalid JSON response. For more information about this error, please see
    any idea why? greetings

    Translated with

    February 20, 2019
    • Yogesh Singh said:

      Hi François,
      If it is working on some pages but not on some page that means the datatable is working fine but because of some fetched records JSON is not properly generating by Datatable. To check the problem – Inspect the page in the browser and navigate to Network and click on the AJAX file name which you are using. The filename will be in red color if response properly not generated and click on it. This will display the issue.

      February 21, 2019

Leave a Reply

Your email address will not be published. Required fields are marked *