AdvancedLesson 14 of 16
Database with PDO – PHP
Prepared statements, transactions and clean queries with PDO.
PDO (PHP Data Objects) is the unified database interface for MySQL/MariaDB, PostgreSQL, SQLite and more. Set error handling to exceptions and the default fetch mode to associative arrays.
<?php
declare(strict_types=1);
$pdo = new PDO(
"mysql:host=localhost;dbname=shop;charset=utf8mb4",
"shop_user",
getenv("DB_PASS") ?: "",
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]
);
// To try it without a server: new PDO("sqlite:" . __DIR__ . "/app.db")Prepared statements separate SQL from data: the values are never built into the query string, which rules out SQL injection. Named (:name) or anonymous (?) placeholders are possible.
<?php
$stmt = $pdo->prepare("SELECT id, name FROM nutzer WHERE email = :email AND aktiv = :aktiv");
$stmt->execute(["email" => $email, "aktiv" => 1]);
$nutzer = $stmt->fetch(); // array or false
if ($nutzer === false) {
exit("Not found");
}
$stmt = $pdo->prepare("INSERT INTO produkte (name, preis) VALUES (?, ?)");
$stmt->execute(["Coffee", 4.5]);
echo "New ID: ", $pdo->lastInsertId(), "\n";
foreach ($pdo->query("SELECT id, name FROM produkte ORDER BY name") as $zeile) {
echo $zeile["id"], ": ", $zeile["name"], "\n";
}Transactions group several statements together: either all succeed or none (example: a bank transfer).
<?php
try {
$pdo->beginTransaction();
$pdo->prepare("UPDATE konten SET saldo = saldo - ? WHERE id = ?")->execute([100, 1]);
$pdo->prepare("UPDATE konten SET saldo = saldo + ? WHERE id = ?")->execute([100, 2]);
$pdo->commit();
} catch (Throwable $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
throw $e;
}For an IN (...) list you generate the matching number of placeholders:
<?php
$ids = [3, 5, 8];
$platz = implode(",", array_fill(0, count($ids), "?"));
$stmt = $pdo->prepare("SELECT * FROM produkte WHERE id IN ($platz)");
$stmt->execute($ids);
$treffer = $stmt->fetchAll();
echo count($treffer), " matches\n";WarningPlaceholders only work for values, not for table names, column names or the
ORDER BY direction. For those you check the input against a fixed allowlist (in_array($spalte, ["name", "preis"], true)).TipPass the connection to repository classes via dependency injection (
new NutzerRepository($pdo)) instead of using a global variable. This makes the code testable.