Code

HTML language code finder

A long table is hard to use. DataTables is a free JavaScript library that adds a search box, click-to-sort columns and pages to any HTML table, with one line of code. Here’s how it works and how to set it up on your hosting.

In this guide

  • try a table with DataTables switched on;
  • see how it works and what it gives your visitors;
  • compare it with building the table yourself in PHP;
  • decide whether you need to set it up yourself;
  • upload it to your hosting in cPanel and switch it on;
  • fill a table from your MySQL database, including tables with thousands of rows.

Try it

This is an ordinary HTML table of example prices with DataTables switched on. Type in the search box, select a column heading to sort by it, and change how many rows show per page.

Example prices for a made-up plumbing business.
JobCategoryFromTypical time
Fix a dripping tapRepairs£651 hour
Unblock a sinkRepairs£751 hour
Replace a toilet cisternRepairs£1802–3 hours
Fit an outside tapInstalls£1202 hours
Install a new radiatorHeating£350Half a day
Power-flush a heating systemHeating£4501 day
Annual boiler serviceHeating£851 hour
Boiler repair call-outHeating£951–2 hours
Fit a new combi boilerHeating£2,4001–2 days
Fit an electric showerBathrooms£4001 day
Full bathroom refitBathrooms£5,5001–2 weeks
Emergency call-outEmergencies£1201 hour

How DataTables works

DataTables doesn’t replace your table. It takes a normal HTML table that’s already on the page and adds the controls around it. That takes three things:

  1. A normal HTML table with a <thead> for the column headings and a <tbody> for the rows.
  2. Two files: a stylesheet (.css) for the look and a script (.js) that does the work.
  3. One line of JavaScript that says which table to switch on: new DataTable('#prices');

When the page loads, the script reads every row into the browser’s memory. From then on, searching, sorting and changing page all happen instantly in the visitor’s browser, without reloading the page or asking your server for anything. It finds numbers, prices and dates by itself, so £2,400 sorts after £350, not before it.

There are three ways to get the rows into the table:

Where the rows come fromHow it worksGood for
In the page (HTML)You type the rows into the page, or your PHP prints them from the database. DataTables enhances what’s there.Most sites: price lists, opening times, staff lists, results — up to a few thousand rows.
Loaded as data (Ajax)The page loads with an empty table; DataTables fetches all the rows as JSON from a URL you give it.Data that changes often, or that other pages and apps use too.
Server-side processingThe browser only ever has one page of rows. Every search, sort or page change asks your server for the next set.Big tables — tens of thousands of rows or more — such as orders, logs or a product catalogue.

Why use it

  • Visitors find things fast. The search box filters every column as they type, so “boiler” finds every boiler job in a 500-row list.
  • Sort by any column — cheapest first, newest first, A to Z. Hold Shift and select a second heading to sort by two columns.
  • Pages instead of one huge scroll. Show 10, 25 or 50 rows at a time, with page numbers and “Showing 1 to 10 of 240”.
  • Hardly any code. One line switches it on. You don’t write any search or sorting code, and nothing changes on your server.
  • Nothing breaks without it. If JavaScript is off or the file fails to load, visitors and search engines still see the full table.
  • Accessible. The search box, menus and column headings all work with a keyboard, and the headings tell screen readers how the table is sorted.
  • Room to grow. Free extensions add export to Excel, CSV and PDF, tables that fit phones (Responsive), and fixed headers. Pick them on the DataTables download page when you need them.
  • Free. DataTables is open source under the MIT licence, for personal and business sites. Only a few add-ons, such as the Editor extension for editing rows, are paid.

DataTables or your own PHP table?

If your rows are in a MySQL database, you have a choice. DataTables does the searching, sorting and paging with JavaScript. Or you can write it yourself in PHP, using PDO to ask the database for each page of results. Both are good; they suit different tables.

DataTablesYour own PHP + PDO table
Who does the workThe visitor’s browser (or your server, in server-side mode)Your server: the database searches, sorts and picks the page
Code to writeOne line of JavaScript, plus PHP to print the rowsAbout 100 lines of PHP and HTML: the queries, the sort links and the page links (full example)
How it feelsInstant — results change as you typeA new page loads for each search, sort or page
Big tablesFine to a few thousand rows; more needs server-side modeAny size, with indexes on the columns you sort by
Without JavaScriptShows every row, with no search or pagesWorks exactly the same
Shareable linksNo — the search and sort aren’t in the addressYes — ?q=boiler&sort=price can be bookmarked, shared or sent back to
Look and wordingDataTables’ controls, which you can restyle and rewordEntirely your own HTML
ExtrasExport to Excel/PDF, phone-friendly layouts and more, as extensionsYou build each one yourself
Best forPrice lists, directories, results and admin screens up to a few thousand rowsVery large lists, pages that must work without JavaScript, and search results people share

You can also have both: PHP and PDO fetch the rows and print them, and DataTables adds the controls on top. That’s what the MySQL section below does.

Do you need to set this up yourself?

Only if you write your own HTML or PHP. With the other ways to build, it’s done for you:

How you buildSortable, searchable tables
Sitejet BuilderYou add tables and lists with the builder’s own elements and settings, so there are no files to upload and no code to write.
WordPressInstall a table plugin such as TablePress, build the table in the editor and tick the features you want. It uses DataTables behind the scenes.
Built with AIAsk your AI tool to “add DataTables to the prices table”. You’ll still upload the files and check it works, as below.
Code it yourselfFollow this guide. It takes about 15 minutes the first time.

Your hosting or a CDN?

The two DataTables files can live on your own hosting or on the free DataTables CDN (a network of servers that send the files to your visitors). Both work. We recommend your own hosting:

On your hosting (recommended)From the DataTables CDN
Set-upDownload two files and upload them in cPanelPaste two lines into your page
PrivacyNothing goes to anyone elseEach visitor’s browser contacts the CDN, which sees their IP address. Mention it in your privacy policy.
If the other site has a problemNot affectedTables lose their controls until it’s back
Security headersWorks with a strict Content-Security-PolicyYour policy has to allow cdn.datatables.net
UpdatesYou replace the two files when you chooseYou change the version number in both links

If you’d rather use the CDN, these are the only two lines you need instead of uploading files (this is version 3.1.6; the download page always shows the latest):

Using the DataTables CDN instead
<!-- In the <head> -->
<link rel="stylesheet" href="https://cdn.datatables.net/3.1.6/css/dataTables.dataTables.min.css">

<!-- Just before </body> -->
<script src="https://cdn.datatables.net/3.1.6/js/dataTables.min.js"></script>

Set it up in cPanel

You’ll download the files, upload them to a folder on your hosting with cPanel Files File Manager, then link to them from your page. If you already upload with FileZilla or your code editor, use that instead of File Manager — see uploading your website.

  1. Choose what you need. Go to datatables.net/download. Under Step 1, choose DataTables styling (or Bootstrap, if your site uses Bootstrap). Under Step 2, leave DataTables ticked and add any extensions you want, such as Responsive.

  2. Download the files. Under Step 3, select the Download tab, leave Minify and Concatenate ticked, and select Download files. Unzip it on your computer: the two files you need are datatables.min.css and datatables.min.js.

  3. Open File Manager. Log in to cPanel (how to log in) and open cPanel Files File Manager.

  4. Make a folder for it. Open public_html, select + Folder and create vendor. Open it and create another folder inside called datatables. Keeping other people’s code in vendor stops it getting mixed up with yours.

  5. Upload the two files. With the datatables folder open, select Upload and drop in datatables.min.css and datatables.min.js. Go back to File Manager and select Reload to check they’re there.

  6. Link to them from your page. Put the stylesheet link in the page’s <head> and the script just before </body>, as in the full example below. The / at the start means “from the top of public_html”, so the same lines work on every page.

  7. Switch it on. Give your table an id, such as id="prices", and add new DataTable('#prices'); in your own script file, loaded after the DataTables script. Upload your page and script.

  8. Check it. Open the page and refresh it with Ctrl+F5 (Cmd+Shift+R on a Mac). You should see the search box, the “per page” menu and arrows on the column headings. No change? See if it doesn’t work.

The complete example

A whole page with one table, using the files you uploaded. It follows the same layout as the structure of a web page.

prices.html
<!DOCTYPE html>
<html lang="en-GB">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Prices | Smith & Sons Plumbing</title>
  <link rel="stylesheet" href="/vendor/datatables/datatables.min.css">
  <link rel="stylesheet" href="/css/style.css">
</head>
<body>
  <main id="main">
    <h1>Our prices</h1>

    <table id="prices" class="display">
      <thead>
        <tr>
          <th>Job</th>
          <th>Category</th>
          <th>From</th>
          <th>Typical time</th>
        </tr>
      </thead>
      <tbody>
        <tr><td>Fix a dripping tap</td><td>Repairs</td><td>£65</td><td data-order="1">1 hour</td></tr>
        <tr><td>Install a new radiator</td><td>Heating</td><td>£350</td><td data-order="4">Half a day</td></tr>
        <tr><td>Fit a new combi boiler</td><td>Heating</td><td>£2,400</td><td data-order="12">1–2 days</td></tr>
        <!-- …one <tr> per row… -->
      </tbody>
    </table>
  </main>

  <script src="/vendor/datatables/datatables.min.js"></script>
  <script src="/js/prices.js"></script>
</body>
</html>
js/prices.js
// /js/prices.js — switch DataTables on for the table with id="prices"
document.addEventListener('DOMContentLoaded', function () {
  new DataTable('#prices');
});
  • Headings go in <thead>, rows in <tbody>. Every row needs the same number of cells as there are headings, or DataTables shows a warning.
  • class="display" gives the table DataTables’ standard look: striped rows and highlighting under the mouse. Leave it out to use only your own styles.
  • data-order tells DataTables what to sort by when the words alone won’t sort properly. “Half a day” has data-order="4" (hours), so it sorts between “2 hours” and “1 day”. Put it on that column in every row.
  • Wait for the page to load. DOMContentLoaded makes sure the table exists before DataTables looks for it.

Change how it behaves

Pass a list of options as the second part of new DataTable(). These are the ones most sites use:

js/prices.js — with options
document.addEventListener('DOMContentLoaded', function () {
  new DataTable('#prices', {
    pageLength: 25,                 // rows per page
    lengthMenu: [10, 25, 50, 100],  // the "per page" choices
    order: [[2, 'asc']],            // start sorted by the 3rd column (counting from 0), cheapest first
    columnDefs: [
      { targets: 3, orderable: false }  // the 4th column can't be sorted
    ],
    language: {
      search: 'Find a job:',
      searchPlaceholder: 'e.g. boiler',
      zeroRecords: 'Nothing matches that search.'
    }
  });
});
OptionWhat it does
pageLengthHow many rows show per page. The default is 10.
lengthMenuThe choices in the “per page” menu.
orderHow the table is sorted when the page opens. Columns are counted from 0, so [[2, 'asc']] is the third column, smallest first; 'desc' is largest first.
columnDefsSettings for particular columns, such as orderable: false (can’t be sorted) or searchable: false (ignored by the search box).
paging, searching, orderingSet any of them to false to turn that feature off — for example, sorting only, with no pages.
languageChange any of the words shown, such as the search label. DataTables also has ready-made translations for other languages.

Every option is listed in the DataTables options reference.

Show rows from your MySQL database

If your rows are in a database, the simplest way is to have PHP print them into the table. DataTables then works exactly as above: it doesn’t know or care that PHP made the rows. You’ll need a database, a user and a password — see create a MySQL database and user. For more on PDO, with examples for adding, changing and deleting rows, see PHP and MySQL with PDO.

First, set up the connection: a config folder in your home folder, outside public_html, holding db-settings.php (your database name, user and password) and db.php (which connects and gives your pages $pdo). Where to keep the connection settings has both files, how to upload them in File Manager, and how to keep the password private.

Then your page loads the rows and prints one <tr> for each:

prices.php
<?php
// /home/mybusin/public_html/prices.php
require __DIR__ . '/../config/db.php';
$jobs = $pdo->query('SELECT job, category, price, hours, time_text FROM jobs ORDER BY job')->fetchAll();
$h = static fn($v): string => htmlspecialchars((string) $v, ENT_QUOTES, 'UTF-8');
?>
<table id="prices" class="display">
  <thead>
    <tr><th>Job</th><th>Category</th><th>From</th><th>Typical time</th></tr>
  </thead>
  <tbody>
  <?php foreach ($jobs as $j): ?>
    <tr>
      <td><?= $h($j['job']) ?></td>
      <td><?= $h($j['category']) ?></td>
      <td>£<?= $h(number_format((float) $j['price'])) ?></td>
      <td data-order="<?= $h($j['hours']) ?>"><?= $h($j['time_text']) ?></td>
    </tr>
  <?php endforeach; ?>
  </tbody>
</table>

This is fine for up to a few thousand rows. Past that, the page gets slow to download, because every row is sent every time.

Thousands of rows? Let the server do the work

With server-side processing, the page starts with an empty table. Each time a visitor searches, sorts or changes page, DataTables sends a short request to a PHP file on your hosting, which returns just the rows for that page as JSON. Visitors download 10 rows instead of 50,000, and the database does the searching.

The table — headings only
<table id="jobs" class="display">
  <thead>
    <tr><th>Job</th><th>Category</th><th>From</th><th>Typical time</th></tr>
  </thead>
</table>
js/jobs.js
document.addEventListener('DOMContentLoaded', function () {
  new DataTable('#jobs', {
    serverSide: true,                          // ask the server for each page
    processing: true,                          // show "Loading…" while it waits
    ajax: { url: '/api/jobs.php', type: 'POST' },
    columns: [
      { data: 'job', render: DataTable.render.text() },       // .text() shows any < > as text, never as code
      { data: 'category', render: DataTable.render.text() },
      { data: 'price', render: DataTable.render.number(',', '.', 0, '£') },
      { data: 'time_text', render: DataTable.render.text(), orderable: false }
    ]
  });
});

The PHP file reads what DataTables sends — which page (start, length), the search words (search[value]) and the sort column (order[0][column], order[0][dir]) — and sends back four things:

api/jobs.php
<?php
// /home/mybusin/public_html/api/jobs.php — answers DataTables' requests with one page of rows
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
require __DIR__ . '/../../config/db.php';

// Only these columns can be sorted. The browser sends a column NUMBER, never a name,
// so nothing the visitor types ever ends up in the SQL itself.
$sortable = ['job', 'category', 'price'];

$draw   = (int) ($_POST['draw'] ?? 0);
$start  = max(0, (int) ($_POST['start'] ?? 0));
$length = (int) ($_POST['length'] ?? 10);
$length = ($length < 1 || $length > 100) ? 10 : $length;
$search = is_string($_POST['search']['value'] ?? null) ? trim($_POST['search']['value']) : '';
$col    = $sortable[(int) ($_POST['order'][0]['column'] ?? 0)] ?? 'job';
$dir    = (($_POST['order'][0]['dir'] ?? 'asc') === 'desc') ? 'DESC' : 'ASC';

$total = (int) $pdo->query('SELECT COUNT(*) FROM jobs')->fetchColumn();

$where  = '';
$params = [];
if ($search !== '') {
    $where  = 'WHERE job LIKE :q1 OR category LIKE :q2';
    $params = [':q1' => "%{$search}%", ':q2' => "%{$search}%"];
}

$count = $pdo->prepare("SELECT COUNT(*) FROM jobs $where");
$count->execute($params);
$filtered = (int) $count->fetchColumn();

$rows = $pdo->prepare("SELECT job, category, price, time_text FROM jobs $where
                       ORDER BY $col $dir LIMIT :start, :length");
foreach ($params as $k => $v) {
    $rows->bindValue($k, $v);
}
$rows->bindValue(':start', $start, PDO::PARAM_INT);
$rows->bindValue(':length', $length, PDO::PARAM_INT);
$rows->execute();

echo json_encode([
    'draw'            => $draw,      // send back the number DataTables sent, so answers can't arrive out of order
    'recordsTotal'    => $total,     // rows in the table
    'recordsFiltered' => $filtered,  // rows that match the search
    'data'            => $rows->fetchAll(),
]);
  • Prepared statements for everything the visitor sends. The search words are bound as :q1 and :q2, and the page numbers as integers, so they can’t change the SQL.
  • A fixed list of sortable columns. Column names can’t be bound in SQL, so the code picks one from $sortable by number. Anything else falls back to job.
  • DataTable.render.text() in the JavaScript. Rows loaded as data are shown as HTML unless you say otherwise. This renderer shows them as plain text — the same job htmlspecialchars() does in the PHP-only version.
  • A limit on page size. Capping length at 100 stops anyone asking for your whole table in one request.
  • Add an index on the columns people sort by, in phpMyAdmin (Structure › Index), to keep it fast as the table grows.

If it doesn’t work

Press F12 in your browser and open the Console tab: DataTables and the browser both explain what went wrong there.

What you seeLikely cause and fix
A plain table, no search boxThe script didn’t load. In the Console, a 404 means the path is wrong: check the folder and file names in File Manager — they’re case-sensitive on the server. DataTable is not defined means your own script ran before the DataTables script: swap the order.
Controls appear but look unstyledThe stylesheet path is wrong, or it’s missing from the <head>.
“Incorrect column count”A row has more or fewer cells than there are headings. Look for a missing </td> or a colspan — DataTables doesn’t support colspan in the body.
“Invalid JSON response”Your PHP file printed an error or a warning before the JSON. Open the PHP file’s address in your browser to see the message, then check cPanel Metrics Errors.
“Ajax error”The ajax URL is wrong or the PHP file crashed. Open the Network tab in F12, select the request and read the Response.
A column sorts in the wrong orderThe cells mix words and numbers. Add data-order with a plain number or a date like 2026-11-26 to that column in every row.
Old version still showingYour browser or Cloudflare is serving a cached copy. Refresh with Ctrl+F5, or purge the cache in Cloudflare.

Hosting with OnPoint Hosts? Every plan includes PHP, MySQL and File Manager, which is all this guide needs.

Ready to build? Every guide on this site was written and tested on OnPoint Hosts — UK cPanel hosting with free SSL and a free first-year domain, from £4.25 a month.

Get hosting

Cookie Preferences Manager

We use strictly necessary cookies to run this site. With your permission we’d also like to use optional cookies to measure site performance and personalise marketing — these stay off until you choose to turn them on. Read our Cookie Policy and Privacy Policy.

Right now this site doesn’t set any optional cookies, whatever you choose.

You can change your mind at any time using the “Cookie settings” link at the bottom of every page.

Optional cookies