الانتقال إلى المحتوى
الأمان (Security)OWASP Top 10· 6 دقائق للقراءة

Escaping Quotes Won't Stop SQL Injection: Parameterized Queries Will

Escaping guards one context, the quoted string. Parameters keep values out of the SQL text entirely, so the database never parses them as code.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • OWASP Top 10 2025
محتويات المقال

A pull request adds a "products by category" query. The reviewer asks about SQL injection, and the author points to the helper that doubles every single quote, with tests to prove it: O'Brien works, and ' OR '1'='1 matches nothing. It gets merged. A week later, a curious customer changes the category in the URL to 0 OR 1=1, and the page lists every product in the table, including a draft price list that was never published. There isn't a single quote in that input.

The common misconception

The belief: is a quoting problem. Escape the quotes in user input, so it can't break out of its string, and the query is safe.

It's half true, which is why it lasts. The textbook attack, ' OR '1'='1, is made of quotes, and escaping really does defuse it inside a string literal: in our test, the condition became Name = ''' OR ''1''=''1' and matched nothing. Escape functions have been around for a long time, and OWASP's own Top 10 still lists escaping as a fallback: "For any residual dynamic queries, escape special characters using the specific escape syntax for that interpreter." So a team that escapes everything feels covered. The problem is everything that isn't a quoted string.

What actually happens

Injection is code and data sharing one string

OWASP's SQL Injection Prevention Cheat Sheet gives the definition: "SQL injection occurs when untrusted data becomes part of a query's SQL syntax." Its community page names the root cause: "SQL makes no real distinction between the control and data planes." When you build a query by gluing strings together, the database's parser decides which characters are code. Escaping is you trying to predict that parser, for every context, in every dialect.

Escaping only protects quoted strings

A number has no quotes to escape. In the story above, CategoryId = {input} became CategoryId = 0 OR 1=1, and because AND binds tighter than OR, the filter on published products disappeared. Structure is worse: the A05:2025 Injection page warns that "SQL structures such as table names, column names, and so on cannot be escaped." And escaping isn't even stable for strings: OWASP notes that it "depends on the SQL dialect and configuration", which is why it calls escaping "STRONGLY DISCOURAGED" as a substitute for parameters.

Escaped data comes back unescaped

Escaping protects one query, once. The database stores O'Brien with its real quote, and the next piece of code that reads it back and glues it into another query is working with raw input again. That's why OWASP says its controls apply "regardless of whether data comes from an HTTP request, another service, or previously stored data."

Parameters keep values out of the SQL text

A sends two things: SQL text with placeholders, and the values, each with a type. In OWASP's words, prepared statements "treat bound values as data rather than SQL syntax." The text never changes, whatever the user types, so there's nothing for input to break out of.

Escaped vs parameterized, on a real database

C# ProductQueries.cs
using Microsoft.Data.SqlClient;public static class ProductQueries{    static string Escape(string s) => s.Replace("'", "''");    public static SqlCommand ByCategory(SqlConnection db, string categoryId) =>        new($"""            SELECT Name, Price FROM Products            WHERE IsPublished = 1 AND CategoryId = {Escape(categoryId)}            """, db);}

We ran these against a throwaway SQL Server database with three published products and one unpublished draft, then read back the statement text SQL Server had cached for each query:

text
-- Escaped, categoryId = "0 OR 1=1": 4 rows, the draft includedSELECT Name, Price FROM ProductsWHERE IsPublished = 1 AND CategoryId = 0 OR 1=1-- Parameterized, categoryId = 2: 2 rows(@categoryId int)SELECT Name, Price FROM ProductsWHERE IsPublished = 1 AND CategoryId = @categoryId

The escaped version handed the input to the parser as SQL. The parameterized text is identical for every request, and the value travels beside it, typed as int. An int can't even hold 0 OR 1=1, so that request fails at parsing, before any SQL is built. The EF Core version produced (@p0 int)SELECT * FROM Products ...: Microsoft documents that FromSql and FromSqlInterpolated "always integrate parameter data as a separate SQL parameter", while FromSqlRaw "can be vulnerable to SQL injection attacks, if improperly used."

Where the input goesEscaping quotesParameters
A string valueWorks, if done right for this dialectSafe
A numberNothing to escape: injectableSafe, and typed
A column or table nameCan't be escapedCan't be a parameter: use an allow-list
Sort direction (ASC/DESC)Can't be escapedCan't be a parameter: use an allow-list
A value read back from the databaseRaw againSafe

How to apply it in your project

  1. Find every query built from stringsSearch for SqlCommand and ExecuteSqlRaw/FromSqlRaw calls that use + or $", and for helpers like .Replace("'", "''"). Each one is a place where input can become code.
  2. Bind every value as a typed parameterUse SqlParameter with a SqlDbType, EF Core LINQ, or FromSql/ExecuteSql with interpolation. Prefer real types such as int and DateTime over strings.
  3. Turn structure into allow-listsColumn names, table names and sort directions come from a fixed map in your code. Unknown values are rejected, not cleaned.
  4. Check inside stored proceduresOWASP warns that binding arguments "protects the call, not dynamic SQL constructed inside the procedure." Inside T-SQL, pass values to sp_executesql as parameters too.
  5. Delete the escape helperOnce the queries are parameterized, remove the helper, so nobody reuses it for the next query.

Key takeaways

  • SQL injection happens when input becomes part of the SQL syntax, not just when it contains quotes.
  • Escaping protects only quoted strings; numbers, identifiers and stored data slip past it.
  • Parameters send SQL text and values separately, so the database never parses input as code.
  • In EF Core, FromSql parameterizes interpolated values and FromSqlRaw doesn't.
  • Map column names and sort directions to an allow-list, because parameters can't hold structure.

📚 المصادر

  1. SQL Injection Prevention Cheat Sheet — OWASP Cheat Sheet Series
  2. Query Parameterization Cheat Sheet — OWASP Cheat Sheet Series
  3. A05:2025 Injection — OWASP Top 10:2025
  4. SQL Injection — OWASP Community
  5. SQL Queries — EF Core, Microsoft Learn

التعليقات (0)