Build a small command-line task list using PHP, PDO, and SQLite. You will add a task, list saved tasks, and search by title while keeping SQL instructions separate from the values entered by the user.
SQLite makes the exercise self-contained: you do not need a database server, a password, or a hosting account. PDO is the PHP interface used to talk to the database. The example demonstrates prepared statements, validation, and error handling; it is not a ready-made web application.
Use PHP 8.1 or later with the PDO SQLite extension enabled. Run this project from a terminal in a folder you can write to. The script intentionally refuses web requests. It stores learning data in a local tasks.sqlite file.
Table of Contents
Check PHP and the database driver
Run php -v to confirm the command-line runtime. Then run php -r 'print_r(PDO::getAvailableDrivers());'. Look for sqlite. PHP can be installed while the required PDO driver is missing, and the PHP used by a web server can differ from the one used in your terminal.
If SQLite is absent, enable or install the PDO SQLite extension through the documentation for your PHP distribution. Do not work around a missing driver by changing unrelated application code. The connection string determines which driver PDO needs.
Create the task-list program
Make a folder named php-pdo-task-list and save this complete program as tasks.php. The first run creates a database and a tasks table in that folder. Use only disposable learning data while experimenting.
<?php
declare(strict_types=1);
if (PHP_SAPI !== 'cli') {
http_response_code(404);
exit;
}
try {
$pdo = new PDO('sqlite:' . __DIR__ . '/tasks.sqlite', null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec('CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL
)');
$action = $argv[1] ?? 'list';
if ($action === 'add') {
$title = trim($argv[2] ?? '');
if ($title === '' || strlen($title) > 120) {
throw new InvalidArgumentException('Use a task title between 1 and 120 bytes.');
}
$statement = $pdo->prepare('INSERT INTO tasks (title) VALUES (:title)');
$statement->execute(['title' => $title]);
echo "Added task #" . $pdo->lastInsertId() . PHP_EOL;
} elseif ($action === 'list' || $action === 'search') {
if ($action === 'search') {
$statement = $pdo->prepare('SELECT id, title FROM tasks WHERE title LIKE :term ORDER BY id');
$statement->execute(['term' => '%' . ($argv[2] ?? '') . '%']);
} else {
$statement = $pdo->query('SELECT id, title FROM tasks ORDER BY id');
}
$rows = $statement->fetchAll();
foreach ($rows as $row) {
echo $row['id'] . ': ' . $row['title'] . PHP_EOL;
}
if (!$rows) echo "No tasks found." . PHP_EOL;
} else {
throw new InvalidArgumentException('Use: php tasks.php add "Title" | list | search "Text"');
}
} catch (InvalidArgumentException $error) {
fwrite(STDERR, $error->getMessage() . PHP_EOL);
exit(1);
} catch (PDOException $error) {
fwrite(STDERR, 'Database operation failed. Check the PDO SQLite extension and folder permissions.' . PHP_EOL);
exit(1);
}
Run the commands in order
Open a terminal in the folder and run these commands. Start with a fresh folder if you want the task IDs to match the output below.
php tasks.php list
php tasks.php add "Read the PDO guide"
php tasks.php add "Build a search command"
php tasks.php list
php tasks.php search "PDO"
The initial list says No tasks found. The two add commands report tasks #1 and #2. Listing then prints both records; searching for PDO prints only the first one.
1: Read the PDO guide
2: Build a search command
Run the list command a second time. The rows remain because they were saved in SQLite, not just held in a PHP variable. A database is useful when data needs to survive the current process.
Why prepare and execute are separate
The insert statement defines its structure once: INSERT INTO tasks (title) VALUES (:title). The execute call supplies the title as data. A title with an apostrophe is still a title; you do not need to build SQL by concatenating and escaping it yourself.
Try adding Review Sam's example inside double quotes in your terminal. Then list the tasks. The apostrophe is stored as part of the value. Shell quoting and SQL parameters solve different problems: quoting a command-line argument keeps spaces together, while binding a value keeps it separate from the SQL statement.
The search command also binds its value. The surrounding percent signs intentionally make it a substring search. A user’s own percent or underscore can still act as a LIKE wildcard; parameter binding prevents SQL injection but does not change the meaning of those pattern characters. Add an explicit escaping policy if your application needs literal substring matching.
Validation and parameters have different jobs
Prepared statements keep values out of SQL syntax. They do not decide whether an empty title, an extremely long value, or an unauthorized operation should be allowed. This example trims the title and accepts 1–120 bytes. That byte limit is deliberately simple; a multilingual user interface should choose and explain a character-counting policy instead.
You also cannot bind a table name or sort keyword through a value placeholder. If a future feature lets users choose an ordering, map a small allowed set such as “oldest” and “newest” to fixed SQL fragments. Never append arbitrary user input as an identifier.
Test the behavior, including mistakes
| Case | Expected result |
|---|---|
| List in a new writable folder | The database is created; no tasks are found. |
| Add a title with an apostrophe | The full title is stored and listed. |
| Add an empty or overlong title | The command exits with an error and inserts no row. |
| Search for text absent from the titles | The command says “No tasks found.” |
| Use an unsupported action | The usage message is printed with a nonzero exit status. |
| Use SQL-looking text as a title | The text is stored as data; the table remains intact. |
Errors you are likely to encounter
“Could not find driver”: the command-line PHP installation lacks PDO SQLite. Check available drivers with the command above. Installing a MySQL driver does not provide SQLite.
Database operation failed: confirm that PHP can create the database in the project folder and the driver is available. The sample gives a short error message rather than dumping internal paths. During local debugging, inspect the exception through your debugger or a private log.
The search is unexpectedly broad: remember the LIKE wildcard rule. Decide whether patterns or literal text are the desired behavior before changing the query.
The page is blank in a browser: that is intentional. This is a CLI project. A browser-facing version needs an HTTP controller, output escaping, CSRF protection for writes, authorization, and a database location outside public access. Do not simply remove the CLI guard and publish the folder.
What changes when using MySQL?
PDO supports multiple databases, but drivers and SQL dialects differ. MySQL needs a server, credentials, a MySQL connection string, and a compatible schema. SQLite’s INTEGER PRIMARY KEY AUTOINCREMENT declaration is not a MySQL table definition. Treat a database migration as a deliberate change and test it against the actual target engine.
For a next exercise, add a done column and a command that updates a task by integer ID. Use a prepared UPDATE statement, validate the ID, and check whether a row was affected. Keep each command small enough that you can describe its inputs, database action, and expected result.
Download the complete example ZIP
The ZIP contains the original example files, a README, and an MIT license. No account or paid dependency is required for these examples.
References and verification
See the PHP manual on prepared statements. This guide was rewritten with AI assistance on October 19, 2026. The displayed program was executed locally with PDO SQLite; checks covered persistence, apostrophes, SQL-looking input, search, invalid commands, empty input, and the byte limit. This verification does not claim MySQL compatibility or production security.
