#Why this matters
Input validation alone cannot make a concatenated SQL query safe: legitimate names like O'Reilly contain apostrophes, and search boxes must accept punctuation. Rejecting characters breaks real users, while manual escaping fails across character encodings.
Securing database access takes two layers. First, separate untrusted data from SQL syntax with prepared statements and strict query patterns. Second, apply least privilege to database roles so a flaw in one endpoint cannot compromise the whole server.
#How prepared statements separate code from data
When an app sends a concatenated string, the SQL parser sees one command and cannot distinguish developer syntax from user input. A native prepared statement splits execution into two steps:
Because the query plan is compiled during PREPARE, bound parameters are evaluated strictly as scalar values, never as SQL keywords, operators, or comments.
#Native prepares in PHP PDO and Python SQLAlchemy
In PHP PDO, disable client-side emulation (ATTR_EMULATE_PREPARES => false) so the database engine performs real preparation, and enable exceptions so errors stay in server logs:
$pdo = new PDO($dsn, $dbUser, $dbPass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$stmt = $pdo->prepare('SELECT id, email FROM accounts WHERE id = :id');
$stmt->execute([':id' => $accountId]);
$row = $stmt->fetch();In Python SQLAlchemy, ORM .where() calls bind values automatically, and raw SQL via text() uses named :param placeholders:
from sqlalchemy import select, text
stmt = select(Item).where(Item.category == user_category)
rows = conn.execute(
text("SELECT id, sku FROM items WHERE category = :cat"),
{"cat": user_category},
).mappings().all()#Handling dynamic ORDER BY and LIKE safely
Prepared statement placeholders only bind data values. They cannot bind table names, column names, or sort directions (ASC, DESC). Writing ORDER BY :sort_col either raises a syntax error or sorts by a constant string.
#Allow-list mapping for identifiers
Never interpolate user input into ORDER BY, GROUP BY, or table names. Map an external key to a hardcoded server-side expression instead:
SORT_MAP = {
"newest": Item.created_at.desc(),
"price_asc": Item.price.asc(),
"price_desc": Item.price.desc(),
}
stmt = select(Item).order_by(SORT_MAP.get(request_sort, Item.created_at.desc()))In PDO, look up $sort in an associative array ($allowed[$sort] ?? 'created_at DESC') before inserting that fixed constant into the query string.
#Parameterizing LIKE without wildcard abuse
Binding f"%{query}%" to :pattern stops SQL injection, yet % and _ inside query remain active LIKE wildcards. Submitting %%%%% can trigger expensive table scans or match unintended records. Escape the escape character first, then % and _, and declare ESCAPE:
def escape_like(value: str, escape_char: str = "\\") -> str:
return (value.replace(escape_char, escape_char * 2)
.replace("%", escape_char + "%")
.replace("_", escape_char + "_"))
pattern = f"%{escape_like(search_term)}%"
stmt = select(Item).where(Item.title.ilike(pattern, escape="\\"))#Least privilege for database accounts
Safe queries protect the syntax boundary; database least privilege limits blast radius if a bug or credential leak occurs. Never connect a web app as a superuser (postgres, root, sa) or schema owner.
| Database role | Allowed privileges | Operational boundary |
|---|---|---|
app_migrator |
CREATE, ALTER, DROP, ownership |
CI/CD deployment jobs only |
app_runtime |
SELECT, INSERT, UPDATE on app tables |
Web workers; no DDL or file I/O |
app_readonly |
SELECT on specific views or tables |
Reporting and public search |
Separating app_migrator from app_runtime ensures a compromised runtime query cannot alter schemas or abuse administrative extensions. Pair role separation with two connection controls:
- TLS and secrets management: require encrypted database transport (
sslmode=verify-fullor equivalent) and load credentials from a secret manager or environment variables, never source control. - Generic client errors: catch database exceptions, log full details server-side, and return an opaque error ID to clients so schema details stay hidden.
#Common mistakes
- Leaving
PDO::ATTR_EMULATE_PREPARESenabled, relying on client-side quoting rather than server-side preparation. - Binding filter values while interpolating
ORDER BY,LIMIT, or table names from user input. - Calling
text()or.raw()in an ORM with f-strings or string concatenation. - Passing unescaped
%and_into parameterizedLIKEpatterns, enabling wildcard DoS. - Connecting as
root/postgres/saand leaking raw SQL exceptions in HTTP responses.
#Summary
Native prepared statements compile SQL structure before binding values, stopping user input from becoming code. For identifiers like ORDER BY columns, enforce a hardcoded allow-list, and escape % and _ wildcards inside parameterized LIKE clauses. Combining safe query construction with least-privilege database roles, TLS connections, and generic error handling contains impact across the stack.