PDO Intro

View saved

Connect with PDO

PDO provides a consistent API for databases. SQLite is handy for local practice.

<?php
$pdo = new PDO("sqlite:" . __DIR__ . "/app.db");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Create a table and insert

Use exec for simple DDL while learning.

$pdo->exec("CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, body TEXT)");
$stmt = $pdo->prepare("INSERT INTO notes (body) VALUES (:body)");
$stmt->execute([":body" => "Hello PDO"]);

Select rows

Prepared statements keep data separate from SQL text.

$stmt = $pdo->query("SELECT id, body FROM notes");
foreach ($stmt as $row) {
  echo $row["id"], ": ", $row["body"], "\n";
}

Database safety

  • Never concatenate untrusted input into SQL
  • Always prefer prepared statements
  • Set exception error mode while developing
  • Close the mental loop: connect, prepare, execute, fetch

Comments

One comment per signed-in account. Comments are saved with this page’s URL.