Code

HTML language code finder

PDO is the part of PHP that talks to your database. These examples cover everything a small site needs — reading, searching, adding, changing and deleting rows — written the safe way, ready to copy.

In this guide

  • create a table in phpMyAdmin;
  • store the connection settings safely outside your website, upload them and test the connection;
  • read rows, and use prepared statements for anything a visitor sends;
  • handle the awkward cases: LIKE, LIMIT, IN lists and sorting;
  • add, change and delete rows, and use transactions;
  • build a searchable, sortable, paged table in PHP, with no JavaScript;
  • understand the error messages.

You’ll need a database and a database user first — see create a MySQL database and user. If you’re deciding between this and DataTables for a table, see DataTables or your own PHP table?

What PDO is, and why use it

PDO (PHP Data Objects) is built into PHP on every OnPoint Hosts plan. Your PHP uses it to send SQL to MySQL or MariaDB and get the results back.

  • Prepared statements keep what visitors type separate from your SQL, which stops SQL injection — the attack that steals or wipes databases.
  • Exceptions: with one setting, any database error stops the script instead of quietly carrying on with missing data.
  • One way of working for MySQL, MariaDB, SQLite, PostgreSQL and more. Only the connection line changes.

You may see older code using mysql_query(). Those functions were removed from PHP years ago and won’t run on a current PHP version. mysqli still works, but PDO is simpler to use safely.

Create your table

Every example on this page uses a jobs table — the same one as the DataTables guide. You need a database and a database user first; the Database Wizard makes both in about two minutes. Write down the full database name, user name and password it gives you.

  1. Open phpMyAdmin. In cPanel, open cPanel Databases phpMyAdmin. It opens already logged in.

  2. Select your database in the list on the left, such as mybusin_site. Check its name is shown at the top before going on, so the table goes into the right database.

  3. Paste the SQL and run it. Open the SQL tab, paste in the code below and select Go.

  4. Check it worked. You’ll see a green message, and jobs appears under your database on the left. Select it to see the four sample rows.

Create the jobs table (phpMyAdmin › SQL)
CREATE TABLE jobs (
    id         INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    job        VARCHAR(100)  NOT NULL,
    category   VARCHAR(30)   NOT NULL,
    price      DECIMAL(8,2)  NOT NULL,
    hours      DECIMAL(5,1)  NOT NULL DEFAULT 1,
    time_text  VARCHAR(30)   NOT NULL DEFAULT '',
    created_at DATETIME      NOT NULL DEFAULT CURRENT_TIMESTAMP,
    INDEX (category),
    INDEX (price)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO jobs (job, category, price, hours, time_text) VALUES
('Fix a dripping tap',         'Repairs',   65,   1,   '1 hour'),
('Install a new radiator',     'Heating',   350,  4,   'Half a day'),
('Fit a new combi boiler',     'Heating',   2400, 12,  '1–2 days'),
('Full bathroom refit',        'Bathrooms', 5500, 60,  '1–2 weeks');
  • id … AUTO_INCREMENT PRIMARY KEY gives every row its own number automatically, so you can find, change or delete exactly one row later.
  • VARCHAR(100) is text up to 100 characters; NOT NULL means it must be filled in.
  • DECIMAL for money, never FLOAT, which rounds pennies.
  • utf8mb4 stores every character, including £, accents and emoji.
  • INDEX on the columns you search and sort by keeps them fast as the table grows.
  • InnoDB is the storage type that supports transactions. It’s the default on cPanel servers.

Need more columns later? Select the table, open Structure and use Add column. Before changing a table that holds real data, export a copy.

Where to keep the connection settings

Your PHP needs four details to connect: the host, the database name, the user and the password. Keep them in one file, outside public_html.

Everything inside public_html can be requested by anyone who guesses the address. Your home folder, one level up, can’t be reached from the web at all — but your PHP can still read it. So the password sits where your pages can use it and nobody else can fetch it.

Where everything goes
/home/mybusin/                  ← your home folder (File Manager opens here)
├── config/                     ← NOT reachable from the web
│   ├── db-settings.php         ← the database name, user and password
│   └── db.php                  ← connects, and gives your pages $pdo
└── public_html/                ← your website: anything in here can be requested
    ├── index.php
    ├── jobs.php                → require __DIR__ . '/../config/db.php';
    └── admin/
        └── add-job.php         → require __DIR__ . '/../../config/db.php';

Use two small files in a config folder: one holds only the settings, and the other does the connecting. When you move the site or change the password, you only edit the first one.

config/db-settings.php — the settings
<?php
// /home/mybusin/config/db-settings.php
// The ONLY place your database password is written down.
// Keep this file outside public_html, out of Git, and out of anything you email or share.
return [
    'host' => 'localhost',
    'name' => 'mybusin_site',        // the FULL database name, with your cPanel prefix
    'user' => 'mybusin_siteuser',    // the FULL database user name
    'pass' => 'paste-the-generated-password-here',
];
config/db.php — the connection
<?php
// /home/mybusin/config/db.php — every page loads this one file to get $pdo
declare(strict_types=1);

$pdo = (static function (): PDO {
    // Read the settings inside this function only, so the password never
    // ends up in a variable your pages could accidentally print
    $s = require __DIR__ . '/db-settings.php';

    try {
        return new PDO(
            "mysql:host={$s['host']};dbname={$s['name']};charset=utf8mb4",
            $s['user'],
            $s['pass'],
            [
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES   => false,
            ]
        );
    } catch (PDOException $e) {
        error_log('Database connection failed: ' . $e->getMessage()); // to your error log, never the page
        http_response_code(503);
        exit('Sorry, something went wrong. Please try again in a few minutes.');
    }
})();
PartWhat it does
return [ … ]The settings file hands its values back to whoever requires it instead of creating variables, and prints nothing. Even if it were opened in a browser, the page would be blank.
static function () { … }The settings are read inside this function and forgotten when it finishes. Your pages get $pdo, never the password.
__DIR__The folder this file is in, so the path works whichever page loads it.
host=localhostThe database is on the same server as your site — always localhost on cPanel hosting.
charset=utf8mb4Sends and receives text in the same character set as the table, so £ and é don’t turn into £.
ERRMODE_EXCEPTIONAny database error throws an exception and stops the script.
FETCH_ASSOCRows come back as $row['job'], without duplicate numbered columns.
EMULATE_PREPARES => falseUses MySQL’s own prepared statements, and numbers come back as numbers.
try … catchIf the connection fails, the reason goes to your error log, and visitors see a polite message instead of your user name.

Upload the settings files

The easiest way is cPanel Files File Manager, because it can reach your home folder. An FTP account limited to public_html (like the one in our FTP guide) can’t see config — which is exactly why it’s a safe place.

  1. Make the config folder in your home folder. Open File Manager. It starts in your home folder (/home/mybusin); if it opens inside public_html, select the Home icon at the top left. Select + Folder, type config and select Create New Folder. Check it sits next to public_html, not inside it.

  2. Create the settings file. Open config, select + File, type db-settings.php and select Create New File. (Or write both files in your code editor and use Upload while config is open.)

  3. Paste in the settings. Right-click db-settings.php and choose Edit (select Edit again if it asks about the character encoding). Paste the settings file from above, replace the name, user and password with your own, and select Save Changes.

  4. Create db.php the same way, in the same config folder, and paste in the connection file. It has no secrets in it, so it’s the same on every site.

  5. Make the settings private. Right-click db-settings.php, choose Change Permissions, leave only User Read and User Write ticked so it shows 600, and select Change Permissions. Other accounts on the server can’t read it.

  6. Test the connection, then delete the test. Upload the test page below to public_html and open https://your-domain/db-test.php. When it says Connected, delete db-test.php straight away. If it says Sorry, something went wrong, see the error messages.

public_html/db-test.php — delete after testing
<?php
// /home/mybusin/public_html/db-test.php — DELETE THIS FILE as soon as it works
declare(strict_types=1);
require __DIR__ . '/../config/db.php';

$version = $pdo->query('SELECT VERSION()')->fetchColumn();
$tables  = $pdo->query('SHOW TABLES')->fetchAll(PDO::FETCH_COLUMN);

echo 'Connected. Database server: ', htmlspecialchars((string) $version), '<br>';
echo 'Tables: ', htmlspecialchars($tables ? implode(', ', $tables) : 'none yet');

Use the connection from your pages

Every page that needs the database starts with one line that loads config/db.php. After it, $pdo is ready to use. The number of ../ is how many folders you go up from the page to your home folder:

The page is in…First line
public_html/jobs.phprequire __DIR__ . '/../config/db.php';
public_html/admin/add-job.phprequire __DIR__ . '/../../config/db.php';
public_html/api/v1/jobs.phprequire __DIR__ . '/../../../config/db.php';

Always start the path with __DIR__. A path such as '../config/db.php' on its own depends on which script PHP started with, and breaks when one file includes another.

Keep the credentials secret

  • Outside public_html, ending in .php. Never store them as .env, .ini, .txt or .inc inside your website, where a browser would show the file as plain text.
  • Permissions 600 on the settings file. Most cPanel servers, OnPoint’s included, run your PHP as your own account, so your pages can still read it. If your site can’t connect afterwards and the error log says Permission denied, set it to 640 and ask support.
  • A database user just for this site, with only the privileges it needs. A site that only reads and writes rows needs SELECT, INSERT, UPDATE, DELETE — not ALL PRIVILEGES (which privileges?). Use a different password from your cPanel login.
  • Never print them. Don’t echo, print_r() or var_dump() the settings, don’t leave phpinfo() or test pages on the server, and keep display_errors off on the live site.
  • Keep them out of Git and shared copies. Add config/db-settings.php to .gitignore, and to the ignore list if your code editor uploads your project. Don’t email it or paste it into chats or AI tools — send the password separately if a developer needs it.
  • If it ever leaks, change the password in cPanel Databases Manage My Databases (Current Users › Change Password) and paste the new one into db-settings.php straight away.

Read rows

When the SQL has no values from a visitor in it, query() runs it straight away. Choose the fetch that matches what you want back:

prices.php
<?php
require __DIR__ . '/../config/db.php';
$h = static fn($v): string => htmlspecialchars((string) $v, ENT_QUOTES, 'UTF-8');

// Many rows: fetchAll() gives you an array of rows
$jobs = $pdo->query('SELECT job, price FROM jobs ORDER BY price')->fetchAll();

// One row: fetch() gives one row, or false if there wasn't one
$cheapest = $pdo->query('SELECT job, price FROM jobs ORDER BY price LIMIT 1')->fetch();

// One value: fetchColumn() gives the first column of the first row
$count = (int) $pdo->query('SELECT COUNT(*) FROM jobs')->fetchColumn();

// id => name pairs, ready for a <select>
$options = $pdo->query('SELECT id, job FROM jobs ORDER BY job')->fetchAll(PDO::FETCH_KEY_PAIR);
?>
<p>We have <?= $count ?> fixed-price jobs, from £<?= $h(number_format((float) $cheapest['price'])) ?>.</p>
<ul>
<?php foreach ($jobs as $j): ?>
  <li><?= $h($j['job']) ?> — £<?= $h(number_format((float) $j['price'])) ?></li>
<?php endforeach; ?>
</ul>

Prepared statements: for anything a visitor sends

As soon as a value comes from a form, the address bar, a cookie or anywhere else outside your code, use prepare() and execute(). You put a placeholder where the value goes, and send the value separately, so it can never change what the SQL does.

Placeholders
<?php
// Question-mark placeholders: values go in, in order
$stmt = $pdo->prepare('SELECT job, price FROM jobs WHERE category = ? AND price <= ?');
$stmt->execute(['Heating', 500]);
$rows = $stmt->fetchAll();

// Named placeholders: easier to read when there are several
$stmt = $pdo->prepare('SELECT job, price FROM jobs WHERE category = :cat AND price <= :max');
$stmt->execute(['cat' => 'Heating', 'max' => 500]);
$rows = $stmt->fetchAll();

// Prepare once, run many times with different values
$stmt = $pdo->prepare('SELECT COUNT(*) FROM jobs WHERE category = ?');
foreach (['Repairs', 'Heating', 'Bathrooms'] as $cat) {
    $stmt->execute([$cat]);
    echo $cat, ': ', $stmt->fetchColumn(), "\n";
}

The awkward cases

Five things that catch everybody out, and how to do each one safely:

LIKE, LIMIT, IN and sorting
<?php
// Read text from the address (?q=boiler) safely: only accept a plain string
$q = is_string($_GET['q'] ?? null) ? trim($_GET['q']) : '';

// 1. LIKE: put the % signs in the VALUE, not in the SQL
$stmt = $pdo->prepare('SELECT job FROM jobs WHERE job LIKE ?');
$stmt->execute(['%' . $q . '%']);

// 2. The same search in two columns needs two names (:q1, :q2) —
//    with real prepared statements a name can only be used once
$stmt = $pdo->prepare('SELECT job FROM jobs WHERE job LIKE :q1 OR category LIKE :q2');
$stmt->execute(['q1' => "%$q%", 'q2' => "%$q%"]);

// 3. LIMIT and OFFSET must be bound as whole numbers
$stmt = $pdo->prepare('SELECT job FROM jobs ORDER BY job LIMIT :limit OFFSET :offset');
$stmt->bindValue(':limit', 10, PDO::PARAM_INT);
$stmt->bindValue(':offset', 20, PDO::PARAM_INT);
$stmt->execute();

// 4. A list of values for IN (…): one ? per value
$ids = [3, 7, 12];
if ($ids) {
    $marks = implode(',', array_fill(0, count($ids), '?'));   // "?,?,?"
    $stmt  = $pdo->prepare("SELECT job FROM jobs WHERE id IN ($marks)");
    $stmt->execute(array_map('intval', $ids));
}

// 5. Column names and ASC/DESC can't be placeholders — choose from a fixed list
$allowed = ['job', 'category', 'price'];
$sort    = is_string($_GET['sort'] ?? null) && in_array($_GET['sort'], $allowed, true) ? $_GET['sort'] : 'job';
$dir     = ($_GET['dir'] ?? '') === 'desc' ? 'DESC' : 'ASC';
$rows    = $pdo->query("SELECT job, price FROM jobs ORDER BY $sort $dir")->fetchAll();
  • Check the type of what visitors send. ?q[]=x in the address turns $_GET['q'] into a list instead of text. is_string() catches that before it causes errors.
  • Sorting by a visitor’s choice is the one place a value goes into the SQL text, so it must come from your own fixed list, never from the request itself.

Add rows from a form

A complete page that adds a job: it checks the form came from your site, checks every value, saves the row, then redirects.

admin/add-job.php
<?php
// /home/mybusin/public_html/admin/add-job.php — put admin pages behind a login
declare(strict_types=1);
session_start();
require __DIR__ . '/../../config/db.php';
$h    = static fn($v): string => htmlspecialchars((string) $v, ENT_QUOTES, 'UTF-8');
$post = static fn(string $k): string => is_string($_POST[$k] ?? null) ? trim($_POST[$k]) : '';

$categories = ['Repairs', 'Heating', 'Bathrooms', 'Installs', 'Emergencies'];
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Stop other websites submitting this form for you (CSRF)
    if (!hash_equals($_SESSION['csrf'] ?? '', $post('csrf'))) {
        http_response_code(400);
        exit('Please reload the page and try again.');
    }

    // Check everything before it goes near the database
    $job      = $post('job');
    $category = $post('category');
    $price    = filter_var($post('price'), FILTER_VALIDATE_FLOAT, ['options' => ['min_range' => 0]]);

    if ($job === '' || mb_strlen($job) > 100)   { $errors[] = 'Enter the job (up to 100 characters).'; }
    if (!in_array($category, $categories, true)) { $errors[] = 'Choose a category.'; }
    if ($price === false)                        { $errors[] = 'Enter a price, like 85 or 85.50.'; }

    if (!$errors) {
        $stmt = $pdo->prepare('INSERT INTO jobs (job, category, price) VALUES (:job, :category, :price)');
        $stmt->execute(['job' => $job, 'category' => $category, 'price' => $price]);
        $newId = (int) $pdo->lastInsertId();

        // Redirect after saving, so refreshing the page doesn't add it twice
        header('Location: /admin/jobs.php?added=' . $newId, true, 303);
        exit;
    }
}
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));
?>
<?php foreach ($errors as $err): ?><p class="error"><?= $h($err) ?></p><?php endforeach; ?>
<form method="post">
  <input type="hidden" name="csrf" value="<?= $h($_SESSION['csrf']) ?>">
  <label>Job <input name="job" maxlength="100" required value="<?= $h($post('job')) ?>"></label>
  <label>Category
    <select name="category">
      <?php foreach ($categories as $c): ?>
        <option<?= $post('category') === $c ? ' selected' : '' ?>><?= $h($c) ?></option>
      <?php endforeach; ?>
    </select>
  </label>
  <label>Price (£) <input name="price" inputmode="decimal" required value="<?= $h($post('price')) ?>"></label>
  <button>Add job</button>
</form>
  • Check values before saving. Placeholders stop SQL injection, but they don’t stop a price of “banana”. Check lengths, numbers and choices yourself.
  • The csrf token proves the form was sent from your own page, so another site can’t trick a logged-in admin’s browser into submitting it.
  • lastInsertId() gives the id MySQL just created, for a link or a confirmation.
  • Redirect after saving (with status 303). Refreshing the page then reloads the list instead of sending the form again.

Change and delete rows

UPDATE and DELETE
<?php
// Change one row — always with a WHERE, always with placeholders
$stmt = $pdo->prepare('UPDATE jobs SET price = :price WHERE id = :id');
$stmt->execute(['price' => 95, 'id' => 7]);

if ($stmt->rowCount() === 0) {
    // No row with that id — or the price was already 95 (MySQL counts only rows it changed)
}

// Remove one row. Only ever do this from a form (POST), never from a link (GET):
// browsers, link checkers and email scanners follow links on their own.
$stmt = $pdo->prepare('DELETE FROM jobs WHERE id = ?');
$stmt->execute([(int) ($_POST['id'] ?? 0)]);
$deleted = $stmt->rowCount();   // 1 if it was there, 0 if not
  • Always include a WHERE. UPDATE jobs SET price = 95 on its own changes every row. Try a SELECT with the same WHERE first if you’re unsure.
  • rowCount() says how many rows changed, so you can tell people “not found” instead of “saved”.
  • Back up first before deleting or changing lots of rows: export the table in phpMyAdmin.

Transactions: all or nothing

When one action needs two or more changes — taking a booking slot and recording the booking, or an order and its items — wrap them in a transaction. If anything fails part-way, rollBack() undoes the lot, so you never end up with half a booking.

A booking, all or nothing
<?php
// Book a slot: both changes happen, or neither does
try {
    $pdo->beginTransaction();

    // Only take the slot if it's still free
    $take = $pdo->prepare('UPDATE slots SET taken = 1 WHERE id = ? AND taken = 0');
    $take->execute([$slotId]);
    if ($take->rowCount() !== 1) {
        throw new RuntimeException('Sorry, someone has just booked that slot.');
    }

    $book = $pdo->prepare('INSERT INTO bookings (slot_id, job_id, email) VALUES (?, ?, ?)');
    $book->execute([$slotId, $jobId, $email]);

    $pdo->commit();      // save both
} catch (Throwable $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack(); // undo both
    }
    throw $e;
}

The AND taken = 0 matters too. If two people press Book at the same moment, only one update can change the slot, and the other person is told it’s gone.

Build a searchable, sortable, paged table

This is the PHP-only alternative to DataTables. The database does the searching, sorting and paging, and each click loads a new page. It needs no JavaScript, and every search and page has its own address (jobs.php?q=boiler&sort=price&dir=desc&page=2) that people can bookmark or share.

jobs.php — the whole page
<?php
// /home/mybusin/public_html/jobs.php — search, sort and pages, all in PHP and SQL
declare(strict_types=1);
require __DIR__ . '/../config/db.php';
$h = static fn($v): string => htmlspecialchars((string) $v, ENT_QUOTES, 'UTF-8');

// 1. Read what the visitor asked for, accepting only values we expect
$columns = ['job' => 'Job', 'category' => 'Category', 'price' => 'From'];   // sortable columns
$sort    = is_string($_GET['sort'] ?? null) && isset($columns[$_GET['sort']]) ? $_GET['sort'] : 'job';
$dir     = ($_GET['dir'] ?? '') === 'desc' ? 'desc' : 'asc';
$q       = is_string($_GET['q'] ?? null) ? trim($_GET['q']) : '';
$perPage = 10;
$page    = max(1, (int) ($_GET['page'] ?? 1));

// 2. The search, with placeholders
$where  = '';
$params = [];
if ($q !== '') {
    $where  = 'WHERE job LIKE :q1 OR category LIKE :q2';
    $params = ['q1' => "%$q%", 'q2' => "%$q%"];
}

// 3. How many rows match, and so how many pages
$count = $pdo->prepare("SELECT COUNT(*) FROM jobs $where");
$count->execute($params);
$total = (int) $count->fetchColumn();
$pages = max(1, (int) ceil($total / $perPage));
$page  = min($page, $pages);

// 4. Just the rows for this page
$stmt = $pdo->prepare("SELECT job, category, price, time_text FROM jobs $where
                       ORDER BY $sort $dir LIMIT :limit OFFSET :offset");
foreach ($params as $k => $v) {
    $stmt->bindValue($k, $v);
}
$stmt->bindValue('limit', $perPage, PDO::PARAM_INT);
$stmt->bindValue('offset', ($page - 1) * $perPage, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll();

// A link to this page with one or two settings changed, keeping the rest
$link = static fn(array $change): string => '?' . http_build_query(
    array_merge(['q' => $q, 'sort' => $sort, 'dir' => $dir, 'page' => $page], $change)
);
?>
<form method="get" role="search">
  <label for="q">Find a job</label>
  <input id="q" name="q" type="search" value="<?= $h($q) ?>">
  <input type="hidden" name="sort" value="<?= $h($sort) ?>">
  <input type="hidden" name="dir" value="<?= $h($dir) ?>">
  <button>Search</button>
</form>

<p><?= $total ?> <?= $total === 1 ? 'job' : 'jobs' ?><?= $q !== '' ? ' matching “' . $h($q) . '”' : '' ?></p>

<table>
  <thead>
    <tr>
    <?php foreach ($columns as $col => $label):
        $on   = $col === $sort;
        $next = $on && $dir === 'asc' ? 'desc' : 'asc'; ?>
      <th scope="col"<?= $on ? ' aria-sort="' . ($dir === 'asc' ? 'ascending' : 'descending') . '"' : '' ?>>
        <a href="<?= $h($link(['sort' => $col, 'dir' => $next, 'page' => 1])) ?>"><?= $h($label) ?><?= $on ? ($dir === 'asc' ? ' ▲' : ' ▼') : '' ?></a>
      </th>
    <?php endforeach; ?>
      <th scope="col">Typical time</th>
    </tr>
  </thead>
  <tbody>
  <?php foreach ($rows as $r): ?>
    <tr>
      <td><?= $h($r['job']) ?></td>
      <td><?= $h($r['category']) ?></td>
      <td>£<?= $h(number_format((float) $r['price'])) ?></td>
      <td><?= $h($r['time_text']) ?></td>
    </tr>
  <?php endforeach; ?>
  <?php if (!$rows): ?>
    <tr><td colspan="4">No jobs match that search.</td></tr>
  <?php endif; ?>
  </tbody>
</table>

<nav aria-label="Pages">
  <?php if ($page > 1): ?><a href="<?= $h($link(['page' => $page - 1])) ?>" rel="prev">‹ Previous</a><?php endif; ?>
  Page <?= $page ?> of <?= $pages ?>
  <?php if ($page < $pages): ?><a href="<?= $h($link(['page' => $page + 1])) ?>" rel="next">Next ›</a><?php endif; ?>
</nav>
PartWhat it does
1. Read the requestTakes the search, sort column, direction and page number from the address, keeping only values on your own lists.
2. The searchAdds WHERE … LIKE only when there’s something to search for, with placeholders.
3. CountCounts the matching rows to work out how many pages there are, and stops someone asking for page 9,000.
4. One page of rowsLIMIT is rows per page; OFFSET skips the earlier pages. Page 3 at 10 per page is LIMIT 10 OFFSET 20.
$link()Builds each heading and page link with the other settings kept, so sorting doesn’t lose the search.
aria-sortTells screen readers which column the table is sorted by.

When something goes wrong

With ERRMODE_EXCEPTION, PDO stops with a message starting SQLSTATE. Check cPanel Metrics Errors or your site’s error_log file for the full message. Keep display_errors switched off on a live site (cPanel Software MultiPHP INI Editor), so visitors never see these.

The message includes…What it means
[1045] Access denied for userWrong username or password, the prefix is missing, or the user hasn’t been added to the database (Manage My Databases).
[1049] Unknown databaseThe database name is wrong — check the prefix.
[2002]PHP can’t reach the database server. Use localhost as the host; if it is, contact support.
[1146] Table … doesn’t existA typo in the table name, or the table is in a different database. Names are case-sensitive on Linux servers.
[1054] Unknown columnA typo in a column name, or the column hasn’t been added yet.
[1064] You have an error in your SQL syntaxLook just before the words quoted in the message: a missing comma, a stray quote, or a column called something like order (wrap reserved words in backticks).
[HY093] Invalid parameter numberThe placeholders and the values don’t match: one too many or too few, a name spelt differently, or the same :name used twice.
[23000] Duplicate entryYou tried to save a value that must be unique (like an email address) and it’s already there. Catch it and tell the person.

Checklist

  • Connection details in one file, outside public_html.
  • charset=utf8mb4, ERRMODE_EXCEPTION, and EMULATE_PREPARES off.
  • Placeholders for every value from outside your code; column names only from a fixed list.
  • Values checked before saving; htmlspecialchars() on everything you print.
  • Changes only by POST, with a CSRF token, behind a login.
  • Transactions when one action makes several changes.
  • Errors logged, never shown to visitors; database backed up.

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