Tech News, Tech & Coding · Free Online Tools

IT Question Answer
Tools
Back to How To Guides
How to Prevent SQL Injection Attacks

How to Prevent SQL Injection Attacks

How To GuidesBy Muhammad Fareed
securitypreventinjectionattacks

Short answer: the most effective defense against SQL injection is to never build SQL by joining strings with user input. Use parameterized queries (prepared statements) so the database treats user input only as data, never as SQL code. Add least-privilege accounts and validation as extra layers.

What is SQL injection?

SQL injection happens when an application puts untrusted input directly into a query, letting an attacker change the meaning of that query. It can expose, change or delete data, and sometimes lead to full server compromise. It has been on the OWASP top risks for years. See the OWASP web vulnerabilities overview.

Keeping user data separate from SQL commands prevents injectionUser input: Untrusted data. Validate: Check type and length. Parameterized query: Data kept apart from SQL. Database: Runs the query safely. Result: No injected commands runUser inputUntrusted dataValidateCheck type and lengthParameterized queryData kept apart from SQLDatabaseRuns the query safelyResultNo injected commands run
Diagram: Keeping user data separate from SQL commands prevents injection.

A vulnerable example

// DO NOT DO THIS
const email = req.body.email;
const sql = "SELECT * FROM users WHERE email = '" + email + "'";
db.query(sql);

If the attacker submits ' OR '1'='1, the query becomes:

SELECT * FROM users WHERE email = '' OR '1'='1'

which returns every user. Worse inputs can read other tables or modify data.

Fix 1: parameterized queries

Node.js (mysql2)

const [rows] = await db.execute(
  "SELECT * FROM users WHERE email = ?",
  [email]
);

Node.js (PostgreSQL, pg)

const result = await client.query(
  "SELECT * FROM users WHERE email = $1",
  [email]
);

Python (sqlite3 / DB-API)

cursor.execute("SELECT * FROM users WHERE email = ?", (email,))

The query structure is sent first and the values separately, so the database never interprets the input as SQL.

Fix 2: use an ORM or query builder correctly

ORMs such as Sequelize, Prisma, SQLAlchemy and Django's ORM generate parameterized queries for you. They are only safe if you avoid raw SQL string building. When you must use raw queries, use the library's parameter placeholders.

Fix 3: whitelist what cannot be parameterized

Table names, column names and sort directions cannot be passed as parameters. Check them against a fixed list:

const allowed = ["name", "created_at"];
const column = allowed.includes(req.query.sort) ? req.query.sort : "created_at";
const sql = "SELECT * FROM posts ORDER BY " + column;

Fix 4: least privilege

The database user your app uses should only have the permissions it needs, for example read and write on its own tables. It should not be an administrator and should not be allowed to drop tables or read system tables. If an injection does happen, the damage is limited.

Fix 5: validate and handle errors

  • Validate type, length and format (an ID should be a number, an email should look like one). Validation helps but is not a replacement for parameterized queries.
  • Never show raw database errors to users; log them privately and return a generic message.
  • Escaping functions are a last resort and easy to get wrong.

Extra defenses

  • A web application firewall can block common attack patterns, but it is a safety net, not a fix.
  • Keep database software and drivers updated.
  • Test with tools and code review; look for string concatenation in queries.
  • Store passwords with a slow hash such as bcrypt so a leaked table is less useful. You can try this with the bcrypt tool.

Checklist

CheckDone when
Parameterized queriesNo query is built by joining strings with input
Dynamic identifiersColumn and table names come from a whitelist
Database accountMinimal privileges
ErrorsNo SQL errors shown to users
TestingInjection attempts included in tests

Also read authentication vs authorization for access control basics.

FAQs

Do ORMs make SQL injection impossible?

No. They protect you when you use their normal query methods. Raw SQL built with string concatenation is still vulnerable.

Is escaping quotes enough?

No. Escaping is error-prone and depends on character sets. Use parameters.

Does NoSQL have injection too?

Yes, a similar problem exists in NoSQL databases when queries are built from unchecked input, for example operators passed in JSON.

How can I test my own site?

Review code for string-built queries and test only systems you own or are authorized to test. Automated scanners can help find obvious issues.