DataTables example with PHP and PDO MySQL

DataTables is an advanced table plugin for jQuery which easily brings features like pagination, searching and ordering for many data sources.

This post is showing how to use DataTables with PHP and MySQL.

For DataTables with Ajax.

datatables example PHP and MySQL

Keep in mind that naturally and especially for larger databases doing a direct PHP to MySQL call would be slower than reading from a cached JSON file…

To use DataTables you will need jQuery and optionally some styling scripts and CSS:

    <title>datatables example</title>
    <link rel="stylesheet" href=""/>
    <script src=""></script>
    <script src=""></script>
    <script src=""></script>
    <link rel="stylesheet" href=""/>

Here I have included Bootstrap.

The base HTML with the table thead and the PHP PDO MySQL query. The query used will fetch all the ‘animals’ from my mock table and order by their id.

<div class="container">
    <div class="row">
        <div class="col-12">
            <div class="card p-2">
                <h3 align="center">Animals</h3>
                <div class="table-responsive">
                    <table id="all_animals" class="table table-striped table-bordered">
                        $select = $db->prepare("SELECT * FROM `MOCK_DATA` ORDER BY `id`;");//Query
                        while ($row = $select->fetch(PDO::FETCH_ASSOC)) {
                            echo '<tr>';
                            echo '<td>' . $row["id"] . '</td>';
                            echo '<td>' . $row["guid"] . '</td> ';
                            echo '<td>' . $row["name"] . '</td>';
                            echo '<td>' . $row["status"] . '</td>';
                            echo '</tr>';

Finally, put the DataTables initiator at the bottom of the page:

<script type="application/javascript">
    $(document).ready(function () {
        $('#all_animals').DataTable({"pageLength": 10, "order": []});

Included are the options for 10 items to be shown each page and no ordering because I used the MySQL query to do the ordering.

If not using the database to order I would have used:

<script type="application/javascript">
    $(document).ready(function () {
        $('#all_animals').DataTable({"pageLength": 10, "order": [[0, 'asc']]});

As 0 is the index for ‘id’ and asc for ascending.