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.
| Job | Category | From | Typical time |
|---|---|---|---|
| Fix a dripping tap | Repairs | £65 | 1 hour |
| Unblock a sink | Repairs | £75 | 1 hour |
| Replace a toilet cistern | Repairs | £180 | 2–3 hours |
| Fit an outside tap | Installs | £120 | 2 hours |
| Install a new radiator | Heating | £350 | Half a day |
| Power-flush a heating system | Heating | £450 | 1 day |
| Annual boiler service | Heating | £85 | 1 hour |
| Boiler repair call-out | Heating | £95 | 1–2 hours |
| Fit a new combi boiler | Heating | £2,400 | 1–2 days |
| Fit an electric shower | Bathrooms | £400 | 1 day |
| Full bathroom refit | Bathrooms | £5,500 | 1–2 weeks |
| Emergency call-out | Emergencies | £120 | 1 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:
- A normal HTML table with a
<thead>for the column headings and a<tbody>for the rows. - Two files: a stylesheet (
.css) for the look and a script (.js) that does the work. - 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 from | How it works | Good 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 processing | The 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.
| DataTables | Your own PHP + PDO table | |
|---|---|---|
| Who does the work | The visitor’s browser (or your server, in server-side mode) | Your server: the database searches, sorts and picks the page |
| Code to write | One line of JavaScript, plus PHP to print the rows | About 100 lines of PHP and HTML: the queries, the sort links and the page links (full example) |
| How it feels | Instant — results change as you type | A new page loads for each search, sort or page |
| Big tables | Fine to a few thousand rows; more needs server-side mode | Any size, with indexes on the columns you sort by |
| Without JavaScript | Shows every row, with no search or pages | Works exactly the same |
| Shareable links | No — the search and sort aren’t in the address | Yes — ?q=boiler&sort=price can be bookmarked, shared or sent back to |
| Look and wording | DataTables’ controls, which you can restyle and reword | Entirely your own HTML |
| Extras | Export to Excel/PDF, phone-friendly layouts and more, as extensions | You build each one yourself |
| Best for | Price lists, directories, results and admin screens up to a few thousand rows | Very 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 build | Sortable, searchable tables |
|---|---|
| Sitejet Builder | You add tables and lists with the builder’s own elements and settings, so there are no files to upload and no code to write. |
| WordPress | Install 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 AI | Ask your AI tool to “add DataTables to the prices table”. You’ll still upload the files and check it works, as below. |
| Code it yourself | Follow 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-up | Download two files and upload them in cPanel | Paste two lines into your page |
| Privacy | Nothing goes to anyone else | Each visitor’s browser contacts the CDN, which sees their IP address. Mention it in your privacy policy. |
| If the other site has a problem | Not affected | Tables lose their controls until it’s back |
| Security headers | Works with a strict Content-Security-Policy | Your policy has to allow cdn.datatables.net |
| Updates | You replace the two files when you choose | You 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):
<!-- 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.
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.
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.cssanddatatables.min.js.Open File Manager. Log in to cPanel (how to log in) and open cPanel Files File Manager.
Make a folder for it. Open
public_html, select + Folder and createvendor. Open it and create another folder inside calleddatatables. Keeping other people’s code invendorstops it getting mixed up with yours.Upload the two files. With the
datatablesfolder open, select Upload and drop indatatables.min.cssanddatatables.min.js. Go back to File Manager and select Reload to check they’re there.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 ofpublic_html”, so the same lines work on every page.Switch it on. Give your table an
id, such asid="prices", and addnew DataTable('#prices');in your own script file, loaded after the DataTables script. Upload your page and script.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.
<!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 — 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-ordertells DataTables what to sort by when the words alone won’t sort properly. “Half a day” hasdata-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.
DOMContentLoadedmakes 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:
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.'
}
});
});| Option | What it does |
|---|---|
pageLength | How many rows show per page. The default is 10. |
lengthMenu | The choices in the “per page” menu. |
order | How 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. |
columnDefs | Settings for particular columns, such as orderable: false (can’t be sorted) or searchable: false (ignored by the search box). |
paging, searching, ordering | Set any of them to false to turn that feature off — for example, sorting only, with no pages. |
language | Change 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:
<?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.
<table id="jobs" class="display">
<thead>
<tr><th>Job</th><th>Category</th><th>From</th><th>Typical time</th></tr>
</thead>
</table>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:
<?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
:q1and: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
$sortableby number. Anything else falls back tojob. 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 jobhtmlspecialchars()does in the PHP-only version.- A limit on page size. Capping
lengthat 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 see | Likely cause and fix |
|---|---|
| A plain table, no search box | The 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 unstyled | The 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 order | The 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 showing | Your 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.