Explain it simply
Explain it simply
SELECT asks the database to 'show me these columns for the rows that match this condition', and it changes nothing. You use it for product lists, blog posts, user tables and contact messages. When any value comes from outside, such as the text from a search box, use a prepared statement so the value travels separately from the SQL command.
On the PHP side it is three steps: prepare() sends the SQL, execute() sends the values, and fetch() collects each row as a PHP array.
Problem → Why → Solution
The problem: user input becomes part of the SQL
A search box seems harmless: take the text, drop it into the query, show the matches. But the database cannot tell which part of the string you wrote and which part the visitor typed, so a visitor who types a quote followed by OR '1'='1' changes the meaning of the whole query. The same code that returns one contact for a normal email returns every row for a crafted one, including columns you never meant to show.
<?php
// DON'T: the visitor's text becomes part of the SQL
$email = $_GET['email'];
$sql = "SELECT id, name, email FROM contacts WHERE email = '$email'";
$result = $pdo->query($sql);
// ?email=aung@example.com -> WHERE email = 'aung@example.com'
// ?email=x' OR '1'='1 -> WHERE email = 'x' OR '1'='1' (every row)Why a prepared statement fixes this
In a prepared statement the SQL goes first with ? holes, so the database has already worked out the shape of the command. The values arrive separately, which means even a value full of quotes is treated as plain data and never becomes part of the command. This is safer than trying to escape things yourself, and harder to forget.
Core concept: SELECT, placeholders and fetching
SELECT reads rows without changing anything. Its anatomy is the columns you want, the table, an optional WHERE filter, an ORDER BY, and optionally LIMIT and OFFSET. Name the columns instead of using SELECT *: you fetch less data, the code keeps working when someone adds a column, and the reader can see which fields the page really uses. ORDER BY is not decoration: without it the database may return rows in any order, and that order can change between runs.
Whenever a value comes from outside, use a prepared statement. prepare() sends the SQL with ? or :name holes to the database, and execute() sends the values separately, so the database never mistakes data for SQL; that separation is what stops SQL injection. Escaping with htmlspecialchars is a different job: it protects the HTML page when you print the values, and you need both. Placeholders stand for values only, not for table names, column names or keywords such as ASC and DESC; for those, choose from a fixed allow-list in PHP.
Fetching comes in several shapes. fetch() returns the next row, or false when the rows run out, which is why while ($row = $stmt->fetch()) works. fetchAll() returns every row as an array and is fine when the result is small and bounded; for large results, looping with fetch() (or foreach over the statement) keeps memory flat. Shortcuts such as fetchColumn(), FETCH_COLUMN and FETCH_KEY_PAIR cover the common shapes. Remember that fetch() on an empty result is false, not an empty array, so reading $row['name'] without checking triggers a warning.
Two details trip people up. execute([...]) binds every value as a string, whereas bindValue(':limit', 10, PDO::PARAM_INT) states the type. This matters for LIMIT and OFFSET on MySQL: with emulated prepares (PDO's default for MySQL) a string value becomes a quoted number after LIMIT, which MySQL rejects as a syntax error. SQLite is more forgiving, which can hide the bug until production. And rowCount() is not a reliable way to count the rows a SELECT returned: the PHP manual says so, and in our SQLite test it reported the rows changed by an earlier INSERT. Use COUNT(*) or count(fetchAll()) instead.
- prepare(): SQL with ? placeholders
- execute(): values travel separately
- fetch(): rows come back one by one
- htmlspecialchars() when printing HTML
Prepared statements protect the database and htmlspecialchars protects the browser; neither replaces the other.
General pattern
<?php
$sql = 'SELECT col_a, col_b FROM table_name WHERE col_a = ? ORDER BY col_b';
$stmt = $pdo->prepare($sql);
$stmt->execute([$value]);
while ($row = $stmt->fetch()) {
// use $row['col_a'] and $row['col_b']
}
// or, instead of the loop: $rows = $stmt->fetchAll();Put ? holes in the SQL and give execute() an array of values; the number of ? marks must equal the number of values. Looping over fetch() gives one row at a time, while fetchAll() gives them all at once.
Example: a prepared SELECT that looks up contacts by email
This example prepares the contacts table with three rows, prepares one statement once and executes it for two emails. The first finds one row, and the second finds nothing and takes the 'not found' path that the code checks for itself. Printing the name and email through htmlspecialchars assumes this output would go into an HTML page.
<?php
$pdo = new PDO('sqlite::memory:', null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec('CREATE TABLE contacts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT NOT NULL,
message TEXT NOT NULL
)');
$pdo->exec("INSERT INTO contacts (name, email, message) VALUES
('Aung Aung', 'aung@example.com', 'I want to learn PHP.'),
('Su Su', 'su@example.com', 'Do you offer evening classes?'),
('Aung Aung', 'aung.work@example.com', 'Second address')");
$stmt = $pdo->prepare('SELECT id, name, email FROM contacts WHERE email = ?');
foreach (['aung@example.com', 'nobody@example.com'] as $searchEmail) {
$stmt->execute([$searchEmail]);
$found = false;
while ($row = $stmt->fetch()) {
$found = true;
echo htmlspecialchars($row['name']), ' - ', htmlspecialchars($row['email']), "\n";
}
if (!$found) {
echo 'No contact with email ', htmlspecialchars($searchEmail), "\n";
}
}Code breakdown
- Line 17
$stmt = $pdo->prepare('SELECT id, name, email FROM contacts WHERE email = ?');Picks three columns by name and leaves a hole for the value in email = ?. prepare() returns a statement object; at this point only the SQL has been sent, with no value yet.
- Line 19
foreach (['aung@example.com', 'nobody@example.com'] as $searchEmail) {A statement is prepared once and can be executed again and again with new values, which helps when one loop runs the same query many times.
- Line 20
$stmt->execute([$searchEmail]);The values in the array fill the ? holes in order (the first value goes to the first ?). Even quotes inside the email stay plain data and cannot change the SQL.
- Line 23
while ($row = $stmt->fetch()) {fetch() hands back one row as an array such as ['id' => ..., 'name' => ..., 'email' => ...], and returns false when the rows run out, which ends the loop. FETCH_ASSOC is the connection's default, so it need not be repeated here.
- Line 25
echo htmlspecialchars($row['name']), ' - ', htmlspecialchars($row['email']), "\n";Text that comes back from the database must also be escaped before it is printed into a web page, so a <script> tag someone stored in a name is not run by the browser. This line has nothing to do with SQL injection; it prevents XSS.
- Line 27
if (!$found) {Handles the empty result explicitly. On the second search the loop body never runs, so $found stays false and the 'No contact...' line is printed.
Aung Aung - aung@example.com
No contact with email nobody@example.comThe ways to fetch
The code below shows four patterns one by one: a row at a time, everything at once, the shortcuts FETCH_COLUMN, FETCH_KEY_PAIR, fetchColumn() and FETCH_OBJ, and the false that fetch() returns for an empty result. Notice that every query returning several rows has an ORDER BY; without it the output would not be stable.
<?php
$pdo = new PDO('sqlite::memory:', null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec('CREATE TABLE contacts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT NOT NULL
)');
$pdo->exec("INSERT INTO contacts (name, email) VALUES
('Aung', 'aung@example.com'), ('Su', 'su@example.com'), ('Mya', 'mya@example.com')");
// 1. One row at a time: fetch() returns false when the rows run out
$stmt = $pdo->query('SELECT id, name FROM contacts ORDER BY id');
while (($row = $stmt->fetch()) !== false) {
echo "row {$row['id']}: {$row['name']}\n";
}
// 2. Everything at once: fine for small, bounded results
$all = $pdo->query('SELECT id, name FROM contacts ORDER BY id')->fetchAll();
echo 'fetchAll gave ', count($all), " rows\n";
// 3. Shortcuts for common shapes
$sql = 'SELECT name FROM contacts ORDER BY id';
$names = $pdo->query($sql)->fetchAll(PDO::FETCH_COLUMN);
echo 'names: ', implode(', ', $names), "\n";
$sql = 'SELECT id, email FROM contacts ORDER BY id';
$byId = $pdo->query($sql)->fetchAll(PDO::FETCH_KEY_PAIR);
echo 'email of 2: ', $byId[2], "\n";
$total = $pdo->query('SELECT COUNT(*) FROM contacts')->fetchColumn();
echo "total: $total\n";
$sql = 'SELECT id, name FROM contacts ORDER BY id LIMIT 1';
$first = $pdo->query($sql)->fetch(PDO::FETCH_OBJ);
echo 'as object: ', $first->name, "\n";
// 4. fetch() on an empty result gives false, not an empty array
$none = $pdo->query('SELECT id FROM contacts WHERE id > 99')->fetch();
var_dump($none);Watching SQL injection happen
This code gives two functions that search a table of two users: findUnsafe() glues the username into the SQL text, while findSafe() binds it with a ?. Watch what the attacker input nobody' OR '1'='1 does to each. The 'Query built' line shows the SQL that really reached the database: one quote closed 'nobody' and added an always-true condition, OR '1'='1', so both rows came back.
<?php
$pdo = new PDO('sqlite::memory:', null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec('CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
api_key TEXT NOT NULL
)');
$pdo->exec("INSERT INTO users (username, api_key) VALUES
('aye', 'key-aye-111'), ('admin', 'key-admin-999')");
function findUnsafe(PDO $pdo, string $username): array
{
$sql = "SELECT username, api_key FROM users WHERE username = '$username' ORDER BY id";
echo "Query built: $sql\n";
return $pdo->query($sql)->fetchAll();
}
function findSafe(PDO $pdo, string $username): array
{
$sql = 'SELECT username, api_key FROM users WHERE username = ? ORDER BY id';
$stmt = $pdo->prepare($sql);
$stmt->execute([$username]);
return $stmt->fetchAll();
}
$attack = "nobody' OR '1'='1";
$leaked = findUnsafe($pdo, $attack);
echo 'Concatenated query returned ', count($leaked), " rows:\n";
foreach ($leaked as $row) {
echo " {$row['username']} -> {$row['api_key']}\n";
}
echo 'Prepared query returned ', count(findSafe($pdo, $attack)), " rows\n";
echo 'Prepared query, honest input: ', count(findSafe($pdo, 'aye')), " row\n";In findSafe() the same input is just one piece of text searched for as a username, nothing matches, and zero rows come back. This demo is deliberately small: real attacks go beyond reading rows and may try to change or delete them, and they sometimes use comment syntax that differs per database (-- or, on MySQL, '-- ' with a space after it). The defence is always the same: use a prepared statement.
Placeholders, LIKE, IN and pagination
To show only a few rows per page, combine LIMIT and OFFSET with an ORDER BY; ending the ORDER BY with a unique column such as id keeps rows from repeating or going missing between pages. Named placeholders (:limit) with bindValue() let you state the type. For an IN list generate one ? per value, and for LIKE put the % wildcards in the value, not in the SQL. (LIKE ignores case for ASCII letters in SQLite, and most default MySQL collations are case-insensitive as well.)
<?php
$pdo = new PDO('sqlite::memory:', null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec('CREATE TABLE contacts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL
)');
$insert = $pdo->prepare('INSERT INTO contacts (name) VALUES (?)');
foreach (['Aung', 'Su', 'Mya', 'Kyaw', 'Hnin', 'Zaw', 'Thida'] as $name) {
$insert->execute([$name]);
}
function page(PDO $pdo, int $page, int $perPage): array
{
$stmt = $pdo->prepare(
'SELECT id, name FROM contacts ORDER BY id LIMIT :limit OFFSET :offset'
);
$stmt->bindValue(':limit', $perPage, PDO::PARAM_INT);
$stmt->bindValue(':offset', ($page - 1) * $perPage, PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetchAll();
}
foreach ([1, 2, 3] as $number) {
$names = array_column(page($pdo, $number, 3), 'name');
echo "Page $number: ", implode(', ', $names), "\n";
}
// A variable-length IN list: one ? per value
$ids = [2, 5, 7];
$marks = implode(',', array_fill(0, count($ids), '?'));
$stmt = $pdo->prepare("SELECT name FROM contacts WHERE id IN ($marks) ORDER BY id");
$stmt->execute($ids);
echo 'IN list: ', implode(', ', $stmt->fetchAll(PDO::FETCH_COLUMN)), "\n";
// LIKE: the wildcards belong in the value, not in the SQL text
$stmt = $pdo->prepare('SELECT name FROM contacts WHERE name LIKE ? ORDER BY name');
$stmt->execute(['%ya%']);
echo 'Names containing "ya": ', implode(', ', $stmt->fetchAll(PDO::FETCH_COLUMN)), "\n";In real projects
Where this shows up in real projects
Every list page you have seen is a SELECT: a product catalog, a blog index, an admin table, search results. It has the columns chosen for the page, a WHERE built from the filters, an ORDER BY from the sort control, and LIMIT/OFFSET for pagination (or a seek condition such as id > last_seen_id on very large tables). Query builders such as Laravel's or Doctrine generate these statements and always bind values, but underneath it is the same prepare, execute and fetch you are learning.
When a page is slow, the next step is to read the SQL and ask the database to explain it (EXPLAIN on MySQL) to see whether an index on a filtered column would help. The data from the SELECT then flows into templates, where output escaping (htmlspecialchars, or the auto-escaping of engines such as Twig and Blade) protects the page. Also take care never to select password hashes or tokens into an array that builds a page when you only need display columns.
Common mistakes
Common mistakes
1. Gluing input into the SQL string
Writing WHERE username = '$name' lets an input containing a quote rewrite the query (the demo in the deeper section returns every row). Use WHERE username = ? with execute([$name]), and do not try to escape things yourself.
2. Using SELECT *
It fetches every column, so you move more data, and if someone later adds a column such as password_hash it can leak into page-building code by accident. Always name the columns.
3. Using the result of fetch() without checking for false
When no row matches, fetch() returns false, and echo $row['name']; prints Warning: Trying to access array offset on false in PHP 8.3 (the wording differs a little between PHP versions) and then the page carries on with an empty value, hiding the bug. Check if ($row === false) first.
4. Putting a placeholder inside quotes
In LIKE '%?%' the ? is inside a string literal, so it is no longer a placeholder; our SQLite test raised 'column index out of range' (the wording varies by driver). Write LIKE ? and put the % signs in the value: execute(['%' . $term . '%']).
5. Trusting rowCount() after a SELECT
According to the PHP manual, rowCount() is not reliable for SELECT across databases. In our SQLite test it printed 3 for a query that matched no rows (the count from an earlier INSERT). Ask for COUNT(*) or count the rows from fetchAll().
Best practices
Best practices
- Name the columns and always add an ORDER BY you can rely on; for pagination end it with a unique column such as id.
- Bind LIMIT and OFFSET with bindValue() and PDO::PARAM_INT, and test on MySQL.
- If ORDER BY must take a column name from outside, check it against a fixed allow-list in PHP, because a placeholder cannot do it.
- Escape output where it enters the page; that is a separate job from preventing SQL injection.
Mini challenge
Mini challenge: a safe product search
Write a search function for a products table. It must return the first matching rows cheapest first, and still be harmless when given a hostile input.
- searchProducts(PDO $pdo, string $term, int $limit): array using a prepared statement with named :term and :limit placeholders
- Products whose name contains the term (LIKE), cheapest first, ties broken by name
- Put the % wildcards in the bound value and bind :limit as an integer
- Try 'cable', 'zzz' and "x' OR '1'='1", printing each result with the price to 2 decimals, or '(no matches)' when empty
<?php
declare(strict_types=1);
// TODO: function searchProducts(PDO $pdo, string $term, int $limit): array
// - prepared statement, named placeholders :term and :limit
// - names containing the term (LIKE), cheapest first, ties broken by name
// - the % wildcards belong in the bound VALUE, and :limit must be bound as an integer
$pdo = new PDO('sqlite::memory:', null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec('CREATE TABLE products (name TEXT NOT NULL, price_cents INTEGER NOT NULL)');
// TODO: insert USB cable 450, Phone case 1200, Cable organizer 800,
// Charging cable 1500, Notebook 300 (prepare once, execute in a loop)
// TODO: for each of 'cable', 'zzz' and "x' OR '1'='1" print "Search for <term>:" and then
// " <name> - <price with 2 decimals>" for each of at most 2 results,
// or " (no matches)" when there are noneExpected: Search for cable: USB cable - 4.50 Cable organizer - 8.00 Search for zzz: (no matches) Search for x' OR '1'='1: (no matches)
Show hint
Use bindValue(':limit', $limit, PDO::PARAM_INT) and show prices with number_format($row['price_cents'] / 100, 2). The hostile input goes into LIKE as ordinary text, so nothing matches it.
Show solution
<?php
declare(strict_types=1);
function searchProducts(PDO $pdo, string $term, int $limit): array
{
$stmt = $pdo->prepare(
'SELECT name, price_cents FROM products
WHERE name LIKE :term
ORDER BY price_cents ASC, name ASC
LIMIT :limit'
);
$stmt->bindValue(':term', '%' . $term . '%');
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetchAll();
}
$pdo = new PDO('sqlite::memory:', null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec('CREATE TABLE products (name TEXT NOT NULL, price_cents INTEGER NOT NULL)');
$insert = $pdo->prepare('INSERT INTO products (name, price_cents) VALUES (?, ?)');
foreach ([['USB cable', 450], ['Phone case', 1200], ['Cable organizer', 800],
['Charging cable', 1500], ['Notebook', 300]] as [$name, $cents]) {
$insert->execute([$name, $cents]);
}
foreach (['cable', 'zzz', "x' OR '1'='1"] as $term) {
echo "Search for $term:\n";
$rows = searchProducts($pdo, $term, 2);
if ($rows === []) {
echo " (no matches)\n";
}
foreach ($rows as $row) {
echo ' ', $row['name'], ' - ', number_format($row['price_cents'] / 100, 2), "\n";
}
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Name the columns and use WHERE, ORDER BY and LIMIT; without an ORDER BY the row order cannot be trusted.
- Send every outside value through prepare() and execute(); a placeholder stands for a value only, wildcards included.
- fetch() gives false when rows run out, fetchAll() gives everything, and shortcuts cover common shapes; do not trust rowCount() after a SELECT.
- Bind LIMIT and OFFSET with bindValue() and PDO::PARAM_INT, and escape results with htmlspecialchars when printing them into a page.
PDO Prepared Statements — PHP Documentation Group