tezvyn:

Preventing SQL injection with parameterized queries

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

Knowing SQL injection and parameterization.

OUTLINE

The flaw is SQL injection; prevent it with parameterized queries/prepared statements (pg $1, mysql2 ?), never string concatenation, so input is data not code.

WHAT THIS TESTS: Whether you recognize SQL injection and understand that parameterization, which separates code from data at the protocol level, is the real fix rather than ad hoc escaping.

A GOOD ANSWER COVERS: The vulnerability is SQL injection. It arises when user input is concatenated directly into a SQL string, letting an attacker inject syntax (for example ' OR '1'='1, or a stacked DROP TABLE) that changes the query's meaning, enabling data theft, authentication bypass, or destruction. The robust prevention is parameterized queries (prepared statements). You write the SQL with placeholders and pass values in a separate array; the database driver sends the query template and the values independently, so values are bound as data and can never be parsed as SQL keywords. In node-postgres (pg) you use numbered placeholders, for example query('SELECT * FROM users WHERE email = $1', [email]). In mysql2 you use ? placeholders with execute, for example execute('SELECT * FROM users WHERE id = ?', [id]). An ORM or query builder that parameterizes under the hood is also fine. Identifiers like table or column names cannot be parameterized and must be validated against an allowlist.

COMMON WRONG ANSWERS: Manually escaping quotes or building a blocklist of dangerous strings, which is fragile and bypassable; relying on input length limits; trusting client-side validation; using string interpolation with template literals and assuming it is safe.

LIKELY FOLLOW-UPS: Why can't you parameterize a table or column name, and what do you do instead? How does an ORM protect you, and when can it still be unsafe (raw queries)? What is second-order SQL injection?

ONE CONCRETE EXAMPLE: Vulnerable: query("SELECT * FROM users WHERE name = '" + name + "'"). With name set to ' OR 1=1 --, every row leaks. Safe: query('SELECT * FROM users WHERE name = $1', [name]) binds the whole string as a literal value, so the malicious payload matches no one.

Read the original → snyk.io

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.