PHP example

How to prevent SQL injection with PDO in PHP

10 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Never put user input into the SQL string. Write a placeholder where the value goes and pass the value separately: $stmt = $pdo->prepare('SELECT * FROM users WHERE name = ?'); then $stmt->execute([$name]);. The database receives the value as data, so input like ' OR '1'='1 matches nothing instead of every row. Placeholders cover values only: table names, column names and ASC/DESC need an allowlist.

SQL injection happens when text from a user is glued into a query and the database runs part of it as SQL. The fix in PHP is PDO's prepared statements: the query and the values travel separately, so a quote in the input is just a character. The old mysql_* functions, including mysql_real_escape_string, were removed in PHP 7.0, and escaping or "sanitizing" input was never the real fix anyway: one forgotten call, a number left unquoted or the wrong character set and the query is open again. The sections below show the injection, then placeholders, bindValue vs bindParam, arrays in IN(), and the two places placeholders can't reach: identifiers and LIKE wildcards. The examples use an in-memory SQLite database so they run anywhere; the PDO code is the same for MySQL and PostgreSQL, and the differences are named where they matter. Each example runs on this page: hit Run, then edit the code and run it again.

1Prepared statements: the injection and the fixRecommended

First the bug. The script below builds a query by putting $input inside the SQL string, the way a login form or a search box often does. The input closes the quote and adds a condition that is always true. Then the same lookup with prepare() and a named placeholder, :name, and the value passed to execute(). The statement is compiled before the value arrives, so nothing in the value can change what the query does.

injection.php
<?php

$pdo = new PDO('sqlite::memory:');
$pdo->exec('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, role TEXT)');
$pdo->exec("INSERT INTO users (name, role) VALUES
    ('alice', 'admin'), ('bob', 'user'), ('carol', 'user')");

// Imagine this came from $_GET['name']
$input = "' OR '1'='1";

// The bug: the input becomes part of the SQL text
$sql = "SELECT name, role FROM users WHERE name = '$input'";
echo $sql, "\n";
$rows = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
echo 'concatenated: ', count($rows), " rows\n";

// The fix: a placeholder, and the value sent separately
$stmt = $pdo->prepare('SELECT name, role FROM users WHERE name = :name');
$stmt->execute(['name' => $input]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo 'prepared: ', count($rows), " rows\n";

// The same statement with a real name
$stmt->execute(['name' => 'bob']);
print_r($stmt->fetch(PDO::FETCH_ASSOC));

Output

The printed SQL shows what went wrong: WHERE name = '' OR '1'='1' is true for every row, so the concatenated query returns 3 rows, including the admin. With the placeholder the database looks for a user whose name is literally ' OR '1'='1 and finds 0 rows. A prepared statement can run again with new values, as the second execute() does to find bob. Use this for every value that comes from outside the script: form fields, URL parameters, cookies, headers, files, and data you read back from your own database.

2Positional and named placeholders

PDO has two placeholder styles. A question mark is positional: pass a list and the values fill the ? marks in order. A named placeholder such as :max takes an array keyed by name, so the order doesn't matter. Pick one style per query. Prepare once and call execute() as many times as you need, which is also faster for bulk inserts. The two connection options shown are the ones worth setting everywhere: errors as exceptions (the default since PHP 8.0, still worth writing for older servers) and associative arrays as the default fetch mode. For MySQL the connection looks like new PDO('mysql:host=localhost;dbname=shop;charset=utf8mb4', $user, $pass, $options); put the character set in the DSN, never in a SET NAMES query.

placeholders.php
<?php

// Same options you would pass for MySQL or PostgreSQL
$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 (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    price REAL NOT NULL,
    stock INTEGER NOT NULL
)');

// Positional placeholders: values go in order
$insert = $pdo->prepare(
    'INSERT INTO products (name, price, stock) VALUES (?, ?, ?)'
);
$items = [
    ['Keyboard', 49.5, 12],
    ['Mouse', 19.99, 0],
    ["Rock 'n' roll mug", 9.0, 40],
];
foreach ($items as $item) {
    $insert->execute($item);  // prepare once, execute many times
}
echo 'last id: ', $pdo->lastInsertId(), "\n";

// Named placeholders: order does not matter
$find = $pdo->prepare(
    'SELECT name, price FROM products
     WHERE price <= :max AND stock > :min ORDER BY price'
);
$find->execute(['min' => 0, 'max' => 50]);
foreach ($find as $row) {
    echo "{$row['name']}: {$row['price']}\n";
}

// One value: fetchColumn()
$count = $pdo->prepare('SELECT COUNT(*) FROM products WHERE stock = ?');
$count->execute([0]);
echo 'out of stock: ', $count->fetchColumn(), "\n";

// Errors throw PDOException (the default since PHP 8.0)
try {
    $pdo->prepare('SELECT nme FROM products');
} catch (PDOException $e) {
    echo $e->getMessage(), "\n";
}

Output

The three inserts reuse one statement, and last id: 3 comes from lastInsertId(). The product name with quotes in it, Rock 'n' roll mug, needs no special handling. The named query finds two products in stock under 50, and fetchColumn() returns a single value (out of stock: 1). The broken query throws a PDOException with no such column: nme instead of failing silently. With MySQL, also set PDO::ATTR_EMULATE_PREPARES => false: by default PDO_MYSQL emulates prepared statements by quoting the values into the SQL itself, which is safe only when the charset is set in the DSN, and it turns every bound value into a quoted string. With emulation off the server prepares the statement for real. SQLite always uses real prepared statements and doesn't support that attribute.

3bindValue vs bindParam, and PDO::PARAM_INT

Instead of passing an array to execute(), you can bind each placeholder first. bindValue() copies the value at the moment you call it. bindParam() binds the variable by reference and reads it only when execute() runs, so a loop can change the variable and execute again. Both take a third argument, the type: PDO::PARAM_STR (the default), PDO::PARAM_INT, PDO::PARAM_BOOL or PDO::PARAM_NULL. An array passed to execute() binds every value as PDO::PARAM_STR, so numbers arrive as text, and that is where the type starts to matter.

bind.php
<?php

$pdo = new PDO('sqlite::memory:');
$pdo->exec('CREATE TABLE tags (id INTEGER PRIMARY KEY, label TEXT)');

// bindParam binds the variable itself; it is read at execute()
$insert = $pdo->prepare('INSERT INTO tags (label) VALUES (:label)');
$insert->bindParam(':label', $label);
foreach (['php', 'sql', 'pdo'] as $label) {
    $insert->execute();
}

// bindValue copies the value now; later changes are ignored
$find = $pdo->prepare('SELECT id FROM tags WHERE label = :label');
$label = 'sql';
$find->bindValue(':label', $label);
$label = 'pdo';
$find->execute();
echo 'bindValue found id ', $find->fetchColumn(), "\n";

$find->bindParam(':label', $label);
$label = 'php';
$find->execute();
echo 'bindParam found id ', $find->fetchColumn(), "\n";

// execute([...]) sends every value as a string (PDO::PARAM_STR)
$type = $pdo->prepare('SELECT typeof(:v)');
$type->execute(['v' => 5]);
echo 'execute([5]): ', $type->fetchColumn(), "\n";
$type->bindValue(':v', 5, PDO::PARAM_INT);
$type->execute();
echo 'PARAM_INT: ', $type->fetchColumn(), "\n";
$type->bindValue(':v', null, PDO::PARAM_NULL);
$type->execute();
echo 'PARAM_NULL: ', $type->fetchColumn(), "\n";

// LIMIT and OFFSET from user input: cast, then bind as an int
$limit = (int) '2';
$page = $pdo->prepare('SELECT label FROM tags ORDER BY id LIMIT :n');
$page->bindValue(':n', $limit, PDO::PARAM_INT);
$page->execute();
echo implode(', ', $page->fetchAll(PDO::FETCH_COLUMN)), "\n";

Output

The two lookups differ only in the bind call. bindValue kept sql, the value $label held when it was called, and found id 2; bindParam read $label at execute(), when it was php, and found id 1. The typeof lines show that execute([5]) sends the integer as text, while PDO::PARAM_INT sends an integer. SQLite forgives a text LIMIT, but MySQL with emulated prepares turns it into LIMIT '2', a syntax error, so cast LIMIT and OFFSET values with (int) and bind them with PDO::PARAM_INT. Since bindParam takes a reference, it needs a variable: a literal like bindParam(1, 5) stops the script with could not be passed by reference.

4Binding an array to IN()

A placeholder holds exactly one value, so IN (?) can't take an array. Build one placeholder per element instead: the SQL text contains only question marks you generated, and the values are still bound. Return early for an empty array, since IN () is a syntax error in MySQL and PostgreSQL. When the query has other parameters too, generate numbered named placeholders and merge them into one array.

in_array.php
<?php

$pdo = new PDO('sqlite::memory:');
$pdo->exec('CREATE TABLE orders (id INTEGER PRIMARY KEY, status TEXT)');
$pdo->exec("INSERT INTO orders (status) VALUES
    ('paid'), ('shipped'), ('paid'), ('refunded'), ('shipped')");

function findByIds(PDO $pdo, array $ids): array
{
    if ($ids === []) {
        return [];  // "IN ()" is invalid SQL in most databases
    }
    // One ? per value: [3, 1, 5] -> "?, ?, ?"
    $marks = implode(', ', array_fill(0, count($ids), '?'));
    $stmt = $pdo->prepare(
        "SELECT id, status FROM orders WHERE id IN ($marks) ORDER BY id"
    );
    $stmt->execute(array_values($ids));
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

foreach (findByIds($pdo, [5, 1, 3]) as $row) {
    echo "{$row['id']} {$row['status']}\n";
}
echo count(findByIds($pdo, [])), " rows for []\n";

// Binding the array as one value does not work
$stmt = $pdo->prepare('SELECT COUNT(*) FROM orders WHERE id IN (?)');
$stmt->execute([implode(',', [5, 1, 3])]);
echo 'IN (?) with "5,1,3": ', $stmt->fetchColumn(), " rows\n";

// IN() plus other values: named placeholders :s0, :s1, ...
$statuses = ['paid', 'shipped'];
$params = ['min' => 2];
$names = [];
foreach (array_values($statuses) as $i => $status) {
    $names[] = ":s$i";
    $params["s$i"] = $status;
}
$sql = 'SELECT id FROM orders WHERE id >= :min AND status IN ('
    . implode(', ', $names) . ')';
echo $sql, "\n";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
echo implode(', ', $stmt->fetchAll(PDO::FETCH_COLUMN)), "\n";

Output

findByIds turns [5, 1, 3] into IN (?, ?, ?) and returns orders 1, 3 and 5; an empty array returns 0 rows for [] without touching the database. Imploding the ids into one string and binding that is the common mistake: the database compares each id with the single text value "5,1,3" and finds 0 rows. The last query mixes a normal parameter with a list; the printed SQL shows the generated IN (:s0, :s1), and the result is 2, 3, 5. array_values() matters when the input array has gaps in its keys, for example after array_filter.

5Table names, columns and ORDER BY: use an allowlist

Placeholders stand for values, not for parts of the SQL grammar. A table name, a column name, ASC or DESC can't be bound, and this is where injection still happens in code that uses PDO everywhere else, typically a sortable table that takes the column from the URL. The safe pattern is an allowlist: map what the user may ask for to SQL you wrote, and fall back to a default for anything else. The user's text never reaches the query.

allowlist.php
<?php

$pdo = new PDO('sqlite::memory:');
$pdo->exec('CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT, year INT)');
$pdo->exec("INSERT INTO books (title, year) VALUES
    ('Neuromancer', 1984), ('Dune', 1965), ('Hyperion', 1989)");

// A placeholder is a value, so ORDER BY ? sorts by a constant string
$stmt = $pdo->prepare('SELECT title FROM books ORDER BY ? DESC');
$stmt->execute(['year']);
echo 'ORDER BY ?: ', implode(', ', $stmt->fetchAll(PDO::FETCH_COLUMN)), "\n";

// And a table or column name can't be a placeholder at all
try {
    $pdo->prepare('SELECT title FROM ?');
} catch (PDOException $e) {
    echo $e->getMessage(), "\n";
}

// The fix: map user input to SQL you wrote yourself
function listBooks(PDO $pdo, string $sort, string $dir): array
{
    $columns = ['title' => 'title', 'year' => 'year', 'added' => 'id'];
    $column = $columns[$sort] ?? 'id';
    $direction = strtolower($dir) === 'desc' ? 'DESC' : 'ASC';
    $sql = "SELECT title FROM books ORDER BY $column $direction";
    return $pdo->query($sql)->fetchAll(PDO::FETCH_COLUMN);
}

echo implode(', ', listBooks($pdo, 'year', 'desc')), "\n";
echo implode(', ', listBooks($pdo, 'title', 'asc')), "\n";
// Anything not on the list falls back to the default
echo implode(', ', listBooks($pdo, 'year; DROP TABLE books', 'x')), "\n";
echo $pdo->query('SELECT COUNT(*) FROM books')->fetchColumn(), " books\n";

Output

ORDER BY ? doesn't fail, which makes it worse: the bound 'year' is a constant string, every row sorts equal, and the books come back in table order (Neuromancer, Dune, Hyperion). A placeholder for a table name is rejected when the statement is prepared: near "?": syntax error. With the allowlist, year and desc sort newest first, and the attack string falls back to the default order with all 3 books still there. The keys the user sends (added) don't have to match column names (id), which keeps your schema out of your URLs.

6LIKE searches with user input

A search box needs LIKE with % around the term. Put the wildcards in the bound value, not in the SQL, and the query is safe from injection. There is a second, smaller problem: % and _ typed by the user are wildcards too, so a search for report_ matches report- as well, and a lone % matches everything. Escape them before adding your own wildcards, and name the escape character with ESCAPE. SQLite has no default escape character; MySQL and PostgreSQL use a backslash, which has its own quoting rules in MySQL strings, so a plain character like ! is the portable choice.

like_search.php
<?php

$pdo = new PDO('sqlite::memory:');
$pdo->exec('CREATE TABLE files (name TEXT)');
$insert = $pdo->prepare('INSERT INTO files (name) VALUES (?)');
$names = ['report_2026.pdf', 'report-2026.pdf', '100% done.txt', 'notes.txt'];
foreach ($names as $name) {
    $insert->execute([$name]);
}

$search = $pdo->prepare(
    'SELECT name FROM files WHERE name LIKE ? ORDER BY name'
);

// Put the wildcards in the bound value, not in the SQL
$term = 'report';
$search->execute(["%$term%"]);
echo implode(' | ', $search->fetchAll(PDO::FETCH_COLUMN)), "\n";

// But % and _ inside the user's text are wildcards too
$term = 'report_';
$search->execute(["%$term%"]);
echo implode(' | ', $search->fetchAll(PDO::FETCH_COLUMN)), "\n";

// Escape them, and name the escape character with ESCAPE
function likeEscape(string $text): string
{
    return str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $text);
}

$safe = $pdo->prepare(
    "SELECT name FROM files WHERE name LIKE ? ESCAPE '!' ORDER BY name"
);
foreach (['report_', '100%', '%', 'notes_'] as $term) {
    $safe->execute(['%' . likeEscape($term) . '%']);
    $found = $safe->fetchAll(PDO::FETCH_COLUMN);
    echo "$term -> ", implode(' | ', $found) ?: '(none)', "\n";
}

Output

The first two lines are identical: report_ without escaping still matches report-2026.pdf, because _ means "any one character". After likeEscape, report_ finds only report_2026.pdf, % finds only the file with a percent sign in its name, and notes_ finds (none). The escape character itself is escaped first, so the order of the arrays in str_replace matters. For a prefix search, add % only at the end.

7Which should you use?

MethodSafe?Use it for
prepare() + execute([...])Yes, for valuesEvery query with outside values
bindValue($k, $v, PDO::PARAM_INT)Yes, typedLIMIT, OFFSET, ints, NULL
bindParam($k, $var)Yes, by referenceRe-running with a changing variable
IN (?, ?, ?) generatedYesA list of ids or values
Allowlist mapYesColumn and table names, ASC/DESC
LIKE ? ESCAPE '!'Yes, and exactSearch boxes
$pdo->quote() / escapingEasy to get wrongAvoid; use placeholders
"... WHERE x = '$input'"NoNever

Frequently asked questions

Are PDO prepared statements enough to prevent SQL injection?

Yes for values, as long as every value goes through a placeholder and none is concatenated into the SQL. They do not protect identifiers or keywords such as a table name, a column name or ASC/DESC; use an allowlist for those. With MySQL, set the charset in the DSN (charset=utf8mb4) and consider PDO::ATTR_EMULATE_PREPARES => false so the server prepares the statement itself. Data read back from your own database is still outside input: bind it too.

What is the difference between bindParam and bindValue?

bindValue() copies the value when you call it. bindParam() binds the variable by reference and reads its current value each time execute() runs, so it suits a loop that changes the variable between executions. bindParam() needs a variable, not a literal. Both accept a type such as PDO::PARAM_INT; an array passed to execute() binds every value as PDO::PARAM_STR, so an integer arrives as text.

How do I bind an array to an IN() clause in PDO?

Generate one placeholder per element and pass the array to execute(): $marks = implode(', ', array_fill(0, count($ids), '?')); then $pdo->prepare("SELECT * FROM t WHERE id IN ($marks)")->execute(array_values($ids));. Handle an empty array before building the query, because IN () is a syntax error in MySQL and PostgreSQL.

How do I sanitize user input for SQL in PHP?

For SQL you do not sanitize, you bind: placeholders keep the value out of the SQL text, so quotes, semicolons and comments in it are harmless. Validate input for your own rules (an id is a positive integer, an email looks like an email), but not as a defense against injection. addslashes(), mysql_real_escape_string() and $pdo->quote() are escaping, and escaping fails when one call is forgotten or the charset is wrong. With SQLite, $pdo->quote("O'Reilly") returns 'O''Reilly', including the quotes, which shows it is meant for building SQL text, not for safety.

Why does LIMIT ? fail with PDO and MySQL?

With emulated prepares, the default for PDO_MYSQL, an array passed to execute() is quoted as strings, so the query becomes LIMIT '10', which MySQL rejects. Bind the value with $stmt->bindValue(':n', (int) $limit, PDO::PARAM_INT), or turn emulation off with PDO::ATTR_EMULATE_PREPARES => false.

What replaced mysql_query and mysql_real_escape_string?

The mysql_* extension was removed in PHP 7.0. Use PDO, which works with MySQL, PostgreSQL, SQLite and others through one API, or mysqli, which is MySQL-only. Both support prepared statements; with mysqli, use $mysqli->prepare() and pass the values to execute() or bind_param() instead of escaping them into the query.

Run it yourself

Open any of these in the full PHP editor to tweak, run and share.

PHP playground