Once a user logs into an application and reaches their account dashboard, the core features usually revolve around managing records—adding new entries, viewing lists, editing details, and deleting items that are no longer needed. Learning how to build a PHP 8 CRUD application with PDO MySQL and pagination gives you the practical foundation behind almost every custom web tool, internal admin panel, and content workflow.

- Advertisement -

Many beginner tutorials throw database queries, form handling, and HTML layout into one tangled file. That works for a tiny test script, but as soon as you add search filters, page numbers, or edit screens, messy code becomes frustrating to debug. Breaking the logic into clean, focused files makes your project much easier to read and expand later.

If your project already includes member accounts and access rules, you can connect record management directly to user sessions and permissions. You can pair this workflow with our guide on How to Build a Secure PHP and MySQL User Profile and Role Based Dashboard to keep protected screens organized by role.

For official PDO behavior, prepared statement rules, and driver options, keep the PHP Manual PDO Reference handy while building your data layer.


Planning the Database Table and Project Structure

Before writing code, decide what data you are storing and how you want to organize the files. For a clear example, let us build a practical tasks and notes manager where each item has a title, category, status, and creation timestamp.

Keep the file layout straightforward so every responsibility has a clear home:

  • db.php — Creates and returns the PDO connection using MySQL and strict error handling.
  • index.php — Displays the paginated list of records, search input, and quick delete action.
  • create.php — Handles adding a new record with server-side validation.
  • edit.php — Loads an existing record by ID and updates changes safely.
  • delete.php — Removes a record via a validated POST request.

Create the MySQL table first so your queries have real columns and indexes to work with:

CREATE TABLE IF NOT EXISTS tasks (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(150) NOT NULL,
    category VARCHAR(60) NOT NULL DEFAULT 'General',
    status ENUM('pending', 'in_progress', 'completed') NOT NULL DEFAULT 'pending',
    notes TEXT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_tasks_status (status),
    INDEX idx_tasks_created (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Adding indexes on status and created_at keeps sorting and filtering fast even after the table grows to tens of thousands of rows.


Step 1: Setting Up the PDO Connection in db.php

A reliable database connection file sets the character encoding to utf8mb4, enables exceptions on errors, disables emulated prepares so MySQL handles parameter binding natively, and returns associative arrays by default.

<?php
declare(strict_types=1);

function getPdoConnection(): PDO
{
    $host = '127.0.0.1';
    $dbname = 'app_crud_demo';
    $username = 'root';
    $password = '';
    $charset = 'utf8mb4';

    $dsn = "mysql:host={$host};dbname={$dbname};charset={$charset}";

    $options = [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ];

    return new PDO($dsn, $username, $password, $options);
}

function e(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

Putting a small e() escaping helper next to the connection function saves typing and reduces the chance of forgetting htmlspecialchars() when printing values inside HTML templates.


Step 2: Creating Records Safely in create.php

When a user submits a form to add a new task, never trust raw input directly. Trim whitespace, check length limits, make sure the status matches allowed values, and insert the row using named placeholders in PDO.

<?php
declare(strict_types=1);

require_once __DIR__ . '/db.php';

$pdo = getPdoConnection();
$errors = [];

$title = '';
$category = 'General';
$status = 'pending';
$notes = '';

$allowedStatuses = ['pending', 'in_progress', 'completed'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim((string) ($_POST['title'] ?? ''));
    $category = trim((string) ($_POST['category'] ?? 'General'));
    $status = (string) ($_POST['status'] ?? 'pending');
    $notes = trim((string) ($_POST['notes'] ?? ''));

    if ($title === '' || mb_strlen($title) < 3) {
        $errors[] = 'Title must be at least 3 characters long.';
    } elseif (mb_strlen($title) > 150) {
        $errors[] = 'Title cannot exceed 150 characters.';
    }

    if ($category === '' || mb_strlen($category) > 60) {
        $errors[] = 'Category must be between 1 and 60 characters.';
    }

    if (!in_array($status, $allowedStatuses, true)) {
        $errors[] = 'Invalid task status selected.';
    }

    if ($errors === []) {
        $sql = 'INSERT INTO tasks (title, category, status, notes)
                VALUES (:title, :category, :status, :notes)';
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            ':title'    => $title,
            ':category' => $category,
            ':status'   => $status,
            ':notes'    => $notes !== '' ? $notes : null,
        ]);

        header('Location: index.php?created=1');
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add New Task</title>
</head>
<body>
    <p><a href="index.php">&larr; Back to Task List</a></p>
    <h1>Create New Task</h1>

    <?php if ($errors !== []): ?>
        <ul>
            <?php foreach ($errors as $error): ?>
                <li><?= e($error) ?></li>
            <?php endforeach; ?>
        </ul>
    <?php endif; ?>

    <form method="post" action="create.php">
        <p>
            <label for="title">Task Title</label><br>
            <input type="text" id="title" name="title" value="<?= e($title) ?>" required>
        </p>

        <p>
            <label for="category">Category</label><br>
            <input type="text" id="category" name="category" value="<?= e($category) ?>" required>
        </p>

        <p>
            <label for="status">Status</label><br>
            <select id="status" name="status">
                <option value="pending" <?= $status === 'pending' ? 'selected' : '' ?>>Pending</option>
                <option value="in_progress" <?= $status === 'in_progress' ? 'selected' : '' ?>>In Progress</option>
                <option value="completed" <?= $status === 'completed' ? 'selected' : '' ?>>Completed</option>
            </select>
        </p>

        <p>
            <label for="notes">Notes (Optional)</label><br>
            <textarea id="notes" name="notes" rows="4"><?= e($notes) ?></textarea>
        </p>

        <button type="submit">Save Task</button>
    </form>
</body>
</html>

Redirecting with header('Location: index.php?created=1') after a successful insert follows the Post/Redirect/Get pattern so refreshing the list page does not duplicate the record.


Step 3: Reading Records with Search and Pagination in index.php

As your table grows, loading every single row at once slows down both the database and the browser. Pagination solves that by fetching only one slice of rows per page using LIMIT and OFFSET, while counting total matching records first so you know how many pages exist.

Supporting a simple search keyword alongside page links makes a PHP 8 CRUD application with PDO MySQL and pagination genuinely useful in day-to-day work. When building pagination in SQL, cast page numbers and limits to strict integers and bind them carefully so unexpected values never break the query.

<?php
declare(strict_types=1);

require_once __DIR__ . '/db.php';

$pdo = getPdoConnection();

$search = trim((string) ($_GET['q'] ?? ''));
$perPage = 10;
$page = max(1, (int) ($_GET['page'] ?? 1));

$whereSql = '';
$params = [];

if ($search !== '') {
    $whereSql = ' WHERE title LIKE :search_title OR category LIKE :search_category';
    $likeTerm = '%' . $search . '%';
    $params[':search_title'] = $likeTerm;
    $params[':search_category'] = $likeTerm;
}

// Count total matching records
$countSql = 'SELECT COUNT(*) FROM tasks' . $whereSql;
$countStmt = $pdo->prepare($countSql);
$countStmt->execute($params);
$totalRows = (int) $countStmt->fetchColumn();

$totalPages = max(1, (int) ceil($totalRows / $perPage));
if ($page > $totalPages) {
    $page = $totalPages;
}

$offset = ($page - 1) * $perPage;

// Fetch current page slice
$dataSql = 'SELECT id, title, category, status, created_at
            FROM tasks' . $whereSql . '
            ORDER BY id DESC
            LIMIT :limit OFFSET :offset';

$dataStmt = $pdo->prepare($dataSql);
foreach ($params as $key => $value) {
    $dataStmt->bindValue($key, $value, PDO::PARAM_STR);
}
$dataStmt->bindValue(':limit', $perPage, PDO::PARAM_INT);
$dataStmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$dataStmt->execute();
$tasks = $dataStmt->fetchAll();

function buildPageUrl(int $targetPage, string $searchQuery): string
{
    $query = ['page' => $targetPage];
    if ($searchQuery !== '') {
        $query['q'] = $searchQuery;
    }
    return 'index.php?' . http_build_query($query);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Task Manager</title>
</head>
<body>
    <h1>Tasks List</h1>

    <p><a href="create.php">+ Add New Task</a></p>

    <?php if (isset($_GET['created'])): ?>
        <p><strong>Task created successfully.</strong></p>
    <?php elseif (isset($_GET['updated'])): ?>
        <p><strong>Task updated successfully.</strong></p>
    <?php elseif (isset($_GET['deleted'])): ?>
        <p><strong>Task deleted.</strong></p>
    <?php endif; ?>

    <form method="get" action="index.php">
        <label for="q">Search:</label>
        <input type="text" id="q" name="q" value="<?= e($search) ?>" placeholder="Title or category">
        <button type="submit">Filter</button>
        <?php if ($search !== ''): ?>
            <a href="index.php">Reset</a>
        <?php endif; ?>
    </form>

    <p>Showing <strong><?= count($tasks) ?></strong> of <strong><?= $totalRows ?></strong> matching tasks (Page <?= $page ?> of <?= $totalPages ?>).</p>

    <table border="1" cellpadding="8" cellspacing="0">
        <thead>
            <tr>
                <th>ID</th>
                <th>Title</th>
                <th>Category</th>
                <th>Status</th>
                <th>Created</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($tasks === []): ?>
                <tr>
                    <td colspan="6">No tasks found.</td>
                </tr>
            <?php else: ?>
                <?php foreach ($tasks as $task): ?>
                    <tr>
                        <td><?= (int) $task['id'] ?></td>
                        <td><?= e((string) $task['title']) ?></td>
                        <td><?= e((string) $task['category']) ?></td>
                        <td><?= e((string) $task['status']) ?></td>
                        <td><?= e((string) $task['created_at']) ?></td>
                        <td>
                            <a href="edit.php?id=<?= (int) $task['id'] ?>">Edit</a> |
                            <form method="post" action="delete.php" style="display:inline;" onsubmit="return confirm('Delete this task?');">
                                <input type="hidden" name="id" value="<?= (int) $task['id'] ?>">
                                <button type="submit">Delete</button>
                            </form>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>

    <?php if ($totalPages > 1): ?>
        <nav aria-label="Pagination">
            <p>
                <?php if ($page > 1): ?>
                    <a href="<?= e(buildPageUrl($page - 1, $search)) ?>">&laquo; Previous</a>
                <?php endif; ?>

                <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                    <?php if ($i === $page): ?>
                        <strong>[<?= $i ?>]</strong>
                    <?php else: ?>
                        <a href="<?= e(buildPageUrl($i, $search)) ?>"><?= $i ?></a>
                    <?php endif; ?>
                <?php endfor; ?>

                <?php if ($page < $totalPages): ?>
                    <a href="<?= e(buildPageUrl($page + 1, $search)) ?>">Next &raquo;</a>
                <?php endif; ?>
            </p>
        </nav>
    <?php endif; ?>
</body>
</html>

Notice how bindValue(':limit', $perPage, PDO::PARAM_INT) and bindValue(':offset', $offset, PDO::PARAM_INT) explicitly bind integers for MySQL LIMIT and OFFSET. When PDO::ATTR_EMULATE_PREPARES is set to false, binding limits as integers avoids subtle type issues.


Step 4: Updating Existing Records in edit.php

Editing a record requires two steps: first fetch the existing row by its numeric ID so the form can pre-fill current values, and then validate and run an UPDATE query when the form is submitted.

<?php
declare(strict_types=1);

require_once __DIR__ . '/db.php';

$pdo = getPdoConnection();

$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
if ($id === null || $id === false) {
    $id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
}

if ($id === null || $id === false) {
    http_response_code(400);
    exit('Invalid task ID.');
}

$selectStmt = $pdo->prepare('SELECT id, title, category, status, notes FROM tasks WHERE id = :id');
$selectStmt->execute([':id' => $id]);
$task = $selectStmt->fetch();

if (!$task) {
    http_response_code(404);
    exit('Task not found.');
}

$errors = [];
$title = (string) $task['title'];
$category = (string) $task['category'];
$status = (string) $task['status'];
$notes = (string) ($task['notes'] ?? '');

$allowedStatuses = ['pending', 'in_progress', 'completed'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim((string) ($_POST['title'] ?? ''));
    $category = trim((string) ($_POST['category'] ?? 'General'));
    $status = (string) ($_POST['status'] ?? 'pending');
    $notes = trim((string) ($_POST['notes'] ?? ''));

    if ($title === '' || mb_strlen($title) < 3) {
        $errors[] = 'Title must be at least 3 characters long.';
    } elseif (mb_strlen($title) > 150) {
        $errors[] = 'Title cannot exceed 150 characters.';
    }

    if ($category === '' || mb_strlen($category) > 60) {
        $errors[] = 'Category must be between 1 and 60 characters.';
    }

    if (!in_array($status, $allowedStatuses, true)) {
        $errors[] = 'Invalid task status selected.';
    }

    if ($errors === []) {
        $updateSql = 'UPDATE tasks
                      SET title = :title, category = :category, status = :status, notes = :notes
                      WHERE id = :id';
        $updateStmt = $pdo->prepare($updateSql);
        $updateStmt->execute([
            ':title'    => $title,
            ':category' => $category,
            ':status'   => $status,
            ':notes'    => $notes !== '' ? $notes : null,
            ':id'       => $id,
        ]);

        header('Location: index.php?updated=1');
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Task #<?= (int) $id ?></title>
</head>
<body>
    <p><a href="index.php">&larr; Back to Task List</a></p>
    <h1>Edit Task #<?= (int) $id ?></h1>

    <?php if ($errors !== []): ?>
        <ul>
            <?php foreach ($errors as $error): ?>
                <li><?= e($error) ?></li>
            <?php endforeach; ?>
        </ul>
    <?php endif; ?>

    <form method="post" action="edit.php?id=<?= (int) $id ?>">
        <input type="hidden" name="id" value="<?= (int) $id ?>">

        <p>
            <label for="title">Task Title</label><br>
            <input type="text" id="title" name="title" value="<?= e($title) ?>" required>
        </p>

        <p>
            <label for="category">Category</label><br>
            <input type="text" id="category" name="category" value="<?= e($category) ?>" required>
        </p>

        <p>
            <label for="status">Status</label><br>
            <select id="status" name="status">
                <option value="pending" <?= $status === 'pending' ? 'selected' : '' ?>>Pending</option>
                <option value="in_progress" <?= $status === 'in_progress' ? 'selected' : '' ?>>In Progress</option>
                <option value="completed" <?= $status === 'completed' ? 'selected' : '' ?>>Completed</option>
            </select>
        </p>

        <p>
            <label for="notes">Notes (Optional)</label><br>
            <textarea id="notes" name="notes" rows="4"><?= e($notes) ?></textarea>
        </p>

        <button type="submit">Update Task</button>
    </form>
</body>
</html>

Validating the ID with filter_input() and returning a clean 404 when a record does not exist prevents ugly database errors or confusing blank screens.


Step 5: Deleting Records Safely in delete.php

Deleting data should always happen on a POST request rather than a plain GET link. Search engines, browser prefetchers, or accidental link clicks can trigger GET URLs, whereas requiring POST makes destructive actions intentional.

<?php
declare(strict_types=1);

require_once __DIR__ . '/db.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit('Method Not Allowed.');
}

$id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
if ($id === null || $id === false) {
    http_response_code(400);
    exit('Invalid task ID.');
}

$pdo = getPdoConnection();
$deleteStmt = $pdo->prepare('DELETE FROM tasks WHERE id = :id');
$deleteStmt->execute([':id' => $id]);

header('Location: index.php?deleted=1');
exit;

If your application uses soft deletes in production (such as setting a deleted_at timestamp instead of removing rows permanently), you can swap the DELETE query for an UPDATE query without changing the rest of the workflow.


Common Pitfalls to Avoid

Even well-structured CRUD scripts run into trouble when small edge cases are overlooked. Keep these practical checks in mind before deploying:

  • String concatenation in SQL: Always bind user input and search terms with prepared statements instead of pasting variables directly into query strings.
  • Unbounded offset pagination: Standard LIMIT and OFFSET works great for typical lists and admin tables, though very deep pages on huge tables can benefit from indexed filters or keyset pagination later.
  • Missing feedback messages: Show clear confirmation notices after create, update, and delete actions so users know their change took effect.

Wrapping Up

Building a PHP 8 CRUD application with PDO MySQL and pagination gives you a clean, repeatable pattern for handling real application data without relying on heavy frameworks. Once you have the core create, read, edit, and delete flow working reliably, you can layer in sorting columns, export buttons, or user ownership checks as your requirements grow.

If your app also handles account sign-ins and forgotten credentials, you can link this module naturally with our guide on How to Build PHP and MySQL Forgot Password and Reset System so users can manage their accounts smoothly from end to end.