Database with PDO
A database keeps the data that outlives a request. In PHP the standard way in is PDO, one interface that speaks to several database engines and keeps user input away from the SQL text.
Connect with PDO
PDO is one interface for many databases. You build it with a DSN string - the database type, host, and name - plus a user and a password. Two options matter from day one: throw exceptions on errors, and fetch associative arrays by default.
<?php $pdo = new PDO( "mysql:host=localhost;dbname=blog;charset=utf8mb4", "blog_user", "secret", [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, ] );
That block needs a MySQL server, and this image has none, so it is not run here. The two examples below use SQLite, which the image carries, and the same PDO calls work on the connection above with another DSN.
SELECT and fetch
Queries that return rows come in two steps: ask, then fetch. query() runs plain SQL with no user input in it; the loop reads one row at a time, so large tables never flood memory.
<?php $pdo = new PDO("sqlite::memory:"); $pdo->exec("CREATE TABLE posts (id INTEGER PRIMARY KEY, title TEXT)"); $pdo->exec("INSERT INTO posts (title) VALUES ('First'), ('Second')"); $stmt = $pdo->query("SELECT id, title FROM posts ORDER BY id DESC"); foreach ($stmt as $row) { echo $row["title"] . PHP_EOL; }
php select.php
Second
First
The table lives in memory for the length of the run, and the descending order puts the newer row first. The loop asks the statement for one row at a time, which is what keeps a large result out of memory.
INSERT with prepare
The moment user input enters SQL, switch from query() to prepare() plus execute(). Values travel separately from the SQL text, so a quote in a name can never break out of its value.
<?php $pdo = new PDO("sqlite::memory:"); $pdo->exec("CREATE TABLE posts (id INTEGER PRIMARY KEY, title TEXT, body TEXT)"); $title = "It's a post"; $body = "Hello"; $stmt = $pdo->prepare("INSERT INTO posts (title, body) VALUES (:title, :body)"); $stmt->execute([":title" => $title, ":body" => $body]); echo $pdo->lastInsertId(), PHP_EOL; $count = $pdo->query("SELECT COUNT(*) FROM posts")->fetchColumn(); echo $count, PHP_EOL;
php insert.php
1
1
The apostrophe in the title goes in as data and the row count proves it arrived as one row. The insert reported the id of the new row, and the query counted it back in the same connection.
Placeholders stop injections
A placeholder is a promise: this spot holds data, never code. The database compiles the statement first and plugs values in later, which is why injections fail by construction. Never concatenate input into SQL when a placeholder can carry it.
Connections, drivers, and practical details live under databases.
Exercises
- Add a third row to select.php and change the order to ORDER BY title.
- Insert two posts in insert.php and print the count after each one.
- Write a SELECT with a placeholder in its WHERE clause and fetch one row by id.
- Switch the SQLite DSN to the MySQL one and read the error that follows, without a server.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is a DSN?
Answer
A string that names the driver, the host and the database
The data source name tells PDO which driver to load and how to reach the database.
-
Which option makes PDO throw an exception on an error?
Answer
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTIONThe error mode decides between silence, warnings and exceptions, and exceptions are the honest default.
-
When must you use
prepare()instead ofquery()?Answer
When user input becomes part of the SQL
The prepared statement keeps the values apart from the SQL text, which is what blocks an injection.
-
Why do placeholders stop SQL injection?
Answer
The values are sent separately from the compiled statement
The database compiles the statement first, so a value can never turn into a second statement.
-
What does this program print?
<?php $pdo = new PDO("sqlite::memory:"); $pdo->exec("CREATE TABLE posts (id INTEGER PRIMARY KEY, title TEXT)"); $pdo->exec("INSERT INTO posts (title) VALUES ('First'), ('Second')"); $stmt = $pdo->query("SELECT title FROM posts ORDER BY id DESC"); foreach ($stmt as $row) { echo $row["title"], PHP_EOL; }Answer
Second / First
The rows are ordered by descending id, so the second insert comes out first.
-
What does this program print?
<?php $pdo = new PDO("sqlite::memory:"); $pdo->exec("CREATE TABLE posts (id INTEGER PRIMARY KEY, title TEXT)"); $pdo->prepare("INSERT INTO posts (title) VALUES (?)")->execute(["Hello"]); echo $pdo->lastInsertId();Answer
1
The first row of a fresh table gets id 1, and lastInsertId reports it.
-
What does this program print?
<?php $pdo = new PDO("sqlite::memory:"); $pdo->exec("CREATE TABLE posts (id INTEGER PRIMARY KEY, title TEXT)"); $stmt = $pdo->prepare("INSERT INTO posts (title) VALUES (:title)"); $stmt->execute([":title" => "It's a post"]); echo $pdo->query("SELECT COUNT(*) FROM posts")->fetchColumn();Answer
1
The apostrophe is part of the value, so one row is stored and counted.
-
What does this program print?
<?php $pdo = new PDO("sqlite::memory:"); $pdo->exec("CREATE TABLE t (name TEXT)"); $pdo->exec("INSERT INTO t VALUES ('Ada')"); $stmt = $pdo->query("SELECT name FROM t"); echo $stmt->fetch()["name"];Answer
Ada
fetch returns the first row, and the name key of that row holds the stored string.
-
Why is
"SELECT id FROM users WHERE name = '" . $name . "'"dangerous?Answer
A quote in the name can change the SQL and run another statement
The input becomes part of the SQL text, so it can close the string and add code of its own.
-
What does
fetchColumn()return afterSELECT COUNT(*)?Answer
The first column of the first row
The method reads one value from the first row, which is the count in this query.
The code on this page was run with PHP 8.5.13 (php -v) in Alpine Linux, with the commands shown above.
Article author: Arthur Isaev