The most secure way to prevent SQL injection in PHP using PDO is to enable true prepared statements (PDO::ATTR_EMULATE_PREPARES => false), configure exceptions on errors (PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION), and pass user input exclusively through bound parameters (? or :named placeholders)—never by interpolating or concatenating variables into the SQL string. Also ensure identifiers (table or column names) are validated against an explicit allowlist because prepared statements only parameterize literal values, not SQL identifiers or keywords.
1. Secure PDO Connection Setup
Disable emulated prepares so the database driver sends the SQL structure and bound parameter values separately.
<?php
declare(strict_types=1);
$dsn = 'mysql:host=127.0.0.1;dbname=app_db;charset=utf8mb4';
$username = 'app_user';
$password = 'strong_password_here';
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $username, $password, $options);
PDO::ATTR_EMULATE_PREPARES => falseuses native prepared statements in the database engine rather than client-side string substitution.charset=utf8mb4ensures consistent character handling across the connection.PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTIONsurfaces database errors cleanly as exceptions instead of failing silently.
2. Parameterized Queries (SELECT, INSERT, UPDATE, DELETE)
Use named placeholders (:email) or positional placeholders (?) and pass values via execute([...]) or bindValue().
<?php
// Safe SELECT with named parameter
$stmt = $pdo->prepare(
'SELECT id, username, role FROM users WHERE email = :email AND is_active = :active'
);
$stmt->execute([
':email' => $emailInput,
':active' => 1,
]);
$user = $stmt->fetch();
// Safe INSERT with positional parameters
$insertStmt = $pdo->prepare(
'INSERT INTO audit_logs (user_id, action_name, ip_address) VALUES (?, ?, ?)'
);
$insertStmt->execute([
(int) $userId,
$actionName,
$ipAddress,
]);
- Never concatenate variables into
$pdo->prepare("SELECT * FROM users WHERE email = '$emailInput'"). - For
LIKEsearches, bind the wildcard pattern with the parameter value rather than concatenating inside the SQL string:
<?php
$searchTerm = '%' . str_replace(['%', '_'], ['\%', '\_'], $rawSearch) . '%';
$stmt = $pdo->prepare('SELECT id, title FROM articles WHERE title LIKE :term');
$stmt->execute([':term' => $searchTerm]);
$results = $stmt->fetchAll();
3. Handling Dynamic Identifiers (Order By, Columns, Tables)
Prepared statements cannot bind table names, column names, ASC/DESC keywords, or IN (...) dynamic lists directly. Validate dynamic identifiers against a strict allowlist:
<?php
$allowedSortColumns = [
'created_at' => 'created_at',
'title' => 'title',
'views' => 'views',
];
$allowedDirections = [
'asc' => 'ASC',
'desc' => 'DESC',
];
$sortCol = $allowedSortColumns[$_GET['sort'] ?? 'created_at'] ?? 'created_at';
$sortDir = $allowedDirections[strtolower($_GET['dir'] ?? 'desc')] ?? 'DESC';
// Safe because $sortCol and $sortDir come strictly from allowlists
$sql = "SELECT id, title, views, created_at FROM articles ORDER BY {$sortCol} {$sortDir} LIMIT :limit";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':limit', 20, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll();
- When
PDO::ATTR_EMULATE_PREPARESisfalse,LIMITorOFFSETvalues often needPDO::PARAM_INTviabindValue()so the driver binds an integer literal rather than a quoted string.
4. Security Checklist for PHP + PDO
- Set
PDO::ATTR_EMULATE_PREPARES => falsein PDO options. - Always use placeholders (
:or?) for data values; never interpolate variables into SQL strings. - Allowlist dynamic column names, sort directions, and table names—never trust raw input for SQL identifiers.
- Use least-privilege database accounts so even a compromised query cannot drop tables or access unrelated schemas.
- Avoid
PDO::ATTR_STRINGIFY_FETCHESsurprises and keepPDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTIONenabled.
