Network Security Basic

What is SQL Injection? How do you prevent it?

AI Practice

What is SQL Injection?

SQL Injection is an attack where the attacker inserts malicious SQL syntax into an input field, manipulating the backend database to execute unintended queries — stealing, modifying, or deleting data, or even gaining system-level access.

Attack Example

Suppose the backend has this query:

// Dangerous: directly concatenating user input into SQL
const query = "SELECT * FROM users WHERE username = '" + username + "' AND password = '" + password + "'"

Attacker enters in the username field:

' OR '1'='1

The resulting SQL becomes:

SELECT * FROM users WHERE username = '' OR '1'='1' AND password = '...'
-- '1'='1' is always true — login bypassed!

More Dangerous Attacks

-- Drop an entire table
'; DROP TABLE users; --

-- Dump all user credentials
' UNION SELECT username, password FROM users --

Prevention

1. Parameterized Queries (most important)

Make the database clearly distinguish between SQL syntax and user-provided data:

// ✅ Safe: using Prepared Statements
const query = 'SELECT * FROM users WHERE username = ? AND password = ?'
db.execute(query, [username, password])

// Node.js + MySQL example
connection.query(
  'SELECT * FROM users WHERE id = ?',
  [userId],
  (err, results) => { /* ... */ }
)

2. Use an ORM

ORMs like Prisma, Sequelize, and TypeORM use parameterized queries by default:

// Prisma (safe by default)
const user = await prisma.user.findUnique({
  where: { username: username }
})

3. Input Validation and Whitelisting

  • Validate input formats (numbers, email format, etc.)
  • Reject input containing SQL keywords (blacklist — secondary defense only)

4. Principle of Least Privilege

Grant the database account only the permissions it needs (SELECT/INSERT), not DROP or DELETE.

5. Don't Expose SQL Details in Error Messages

// ❌ Dangerous: reveals database structure
res.json({ error: "SQL Error: Table 'users' doesn't exist" })

// ✅ Safe: generic error message
res.status(500).json({ error: 'Server error, please try again later' })

✦ AI Mock Interview

Type your answer and get instant AI feedback

Sign in to use AI scoring

Copyright © 2026 Wood All Rights Reserved · FE Interview Hub