Create Datatables AJAX pagination from PostgreSQL with PHP

With pagination, you can display lots of data on the page in an effective way.

You can implement this easily using DataTables jQuery plugin.

In this tutorial, I show how you can create DataTables AJAX pagination with search and sort from PostgreSQL database using PHP.

Create Datatables AJAX pagination from PostgreSQL with PHP


  1. Table structure
  2. Configuration
  3. Download and Include
  4. HTML
  5. PHP
  6. jQuery
  7. Output
  8. Conclusion

1. Table structure

I am using employees table in the example. It has the following structure –

CREATE TABLE employees (
    id serial PRIMARY KEY,
    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 database configuration.

Completed Code


$host = "localhost";
$user = "postgres";
$password = "root";
$dbname = "tutorial";
$con = pg_connect("host=$host dbname=$dbname user=$user password=$password");

if (!$con) {
   die('Connection failed.');

3. Download and Include

  • Download Datatables from here.
  • Include datatables.min.css, jQuery library, and datatables.min.js.
  • 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. PHP

Create ajaxfile.php file.

Read DataTables POST values and assigned them to variables.

Count total records with and without search filter from the employees table.

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

NOTE – Array key names must be same as defined in the columns option while initializing DataTables.

Initialize $response Array with required values and return in JSON format.

Completed Code

## Database configuration
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

## Search 
$searchQuery = "";
$searchQueryVal = array();

if($searchValue != ''){
     $searchQuery .= " where (emp_name ilike $1 or 
          email ilike $2 or 
          city ilike $3) ";

     $searchQueryVal[] = '%'.$searchValue.'%';
     $searchQueryVal[] = '%'.$searchValue.'%';
     $searchQueryVal[] = '%'.$searchValue.'%';


## Total number of records without filter
$sql = "select count(*) as allcount from employees";
$result = pg_query($con,$sql);
$records = pg_fetch_assoc($result);
$totalRecords = $records['allcount'];

## Total number of record with filter
$sql = "select count(*) as allcount from employees ".$searchQuery;
$result = pg_query_params($con,$sql,$searchQueryVal);
$records = pg_fetch_assoc($result);
$totalRecordwithFilter = $records['allcount'];

## Fetch records
$sql = "select * from employees ".$searchQuery." order by ".$columnName." ".$columnSortOrder." limit $rowperpage OFFSET $row";

$empRecords = pg_query_params($con,$sql,$searchQueryVal);
$data = array();

while ($row = pg_fetch_assoc($empRecords)) {
    $data[] = array( 

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

echo json_encode($response);

6. jQuery

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

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

In the columns option pass key names that get read on AJAX successfully callback.

Completed Code

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

7. Output

View Output

8. Conclusion

If you are getting JSON error while loading the page then check the SQL queries again and return response and use the browser network tab to debug.

You can view the MySQL version of this tutorial here.

If you found this tutorial helpful then don't forget to share.

3 thoughts on “Create Datatables AJAX pagination from PostgreSQL with PHP”

  1. $searchQuery = “id>$1”;

    Does this only work for auto-incrementing tables? And where does that identification come from? It seemed to me that it required a boolean value, what could I do for non-incrementable tables? Thank you.


Leave a Comment