Databases with PDO and SQLite
A real application stores its data permanently: users, articles, orders. Databases are used for that. PHP includes PDO (PHP Data Objects), a single interface to talk to MySQL, PostgreSQL, SQLite and other engines with the same code. In this course we use SQLite because it keeps the whole database in a single file, needs no server installation and is perfect for learning. If your PHP installation does not have it enabled, enable the line extension=pdo_sqlite in php.ini and restart. Check with php -m that pdo_sqlite appears.
Connecting and creating tables
You connect by creating a PDO object with a DSN, the text that indicates the engine and the location. The three recommended options: ERRMODE_EXCEPTION so errors throw exceptions instead of passing silently, FETCH_ASSOC to receive rows as associative arrays and EMULATE_PREPARES set to false so prepared statements are real. With exec() you run statements that return no rows, such as CREATE TABLE. Keep the database file outside the server's public folder, so nobody can download it.
<?php
// File: src/db.php
declare(strict_types=1);
function connect(string $file): PDO
{
$pdo = new PDO('sqlite:' . $file, null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
$pdo->exec('PRAGMA foreign_keys = ON');
return $pdo;
}
function migrate(PDO $pdo): void
{
$pdo->exec('
CREATE TABLE IF NOT EXISTS notes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
body TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
)
');
}Prepared statements: the defense against SQL injection
SQL injection happens when you build a query by pasting user text into the statement. If someone types ' OR '1'='1 in a field, the text stops being data and becomes part of the statement, and the attacker can read, modify or delete the whole database. Never build SQL by concatenating variables. The solution is prepared statements: you write the statement with placeholders (? or :name) and send the values separately; the engine always treats them as data, never as code, whatever they contain.
<?php
declare(strict_types=1);
require_once __DIR__ . '/src/db.php';
$pdo = connect(__DIR__ . '/data.sqlite');
migrate($pdo);
// INSERT with named placeholders
$insert = $pdo->prepare('INSERT INTO notes (title, body) VALUES (:title, :body)');
$insert->execute([':title' => 'First note', ':body' => "O'Reilly said: DROP TABLE notes; --"]);
$id = (int) $pdo->lastInsertId();
echo "Inserted note $id\n";
// SELECT one row
$select = $pdo->prepare('SELECT id, title, body FROM notes WHERE id = ?');
$select->execute([$id]);
$note = $select->fetch(); // array or false
echo $note['title'] ?? 'not found', "\n";
// SELECT many rows
foreach ($pdo->query('SELECT id, title FROM notes ORDER BY id DESC') as $row) {
echo $row['id'], ': ', $row['title'], "\n";
}
// UPDATE and DELETE
$update = $pdo->prepare('UPDATE notes SET title = :title WHERE id = :id');
$update->execute([':title' => 'Renamed', ':id' => $id]);
echo $update->rowCount(), " row updated\n"; // 1 row updated
$delete = $pdo->prepare('DELETE FROM notes WHERE id = ?');
$delete->execute([$id]);Notice that the dangerous text in the example is stored as harmless text: the quote and the DROP TABLE are just characters. An important detail: placeholders can only replace values, not table names, column names or the ORDER BY direction. If you need a user-chosen order, compare their choice against a fixed whitelist of allowed options and use only those that match. With query() only statements with no external data are run; as soon as there is user data, use prepare().
Transactions
A transaction groups several operations so that all of them run or none does. Imagine transferring money: subtract from one account and add to another; if the second fails, the first must be undone. With beginTransaction() you start, with commit() you confirm and with rollBack() you undo. Place them inside a try/catch to undo on any exception. In addition, transactions make many inserts much faster in SQLite.
<?php
declare(strict_types=1);
function transfer(PDO $pdo, int $from, int $to, float $amount): void
{
$pdo->beginTransaction();
try {
$debit = $pdo->prepare('UPDATE accounts SET balance = balance - :a WHERE id = :id');
$debit->execute([':a' => $amount, ':id' => $from]);
$credit = $pdo->prepare('UPDATE accounts SET balance = balance + :a WHERE id = :id');
$credit->execute([':a' => $amount, ':id' => $to]);
$pdo->commit();
} catch (Throwable $e) {
$pdo->rollBack();
throw $e;
}
}检验所学
第 1 / 1How is SQL injection prevented?
✎ 我的笔记
仅保存在此浏览器中。登录后可保存到账号。0/5000 字符