SQL injection (SQLi) is still one of the most common web vulnerabilities, and it is easy to prevent once you know the pattern. This guide explains it with small examples. Only test on systems you own or have written permission to test.
What goes wrong
Suppose a login query is built by joining strings:
# UNSAFE query = "SELECT * FROM users WHERE email = '" + email + "' AND password = '" + password + "'" If an attacker enters this as the email:
' OR '1'='1' -- the query becomes:
SELECT * FROM users WHERE email = '' OR '1'='1' --' AND password = '' '1'='1' is always true and -- comments out the rest, so the check passes. The input was treated as SQL code instead of data.
The fix: parameterised queries
Send the SQL and the values separately. The database never treats values as code.
# SAFE (Python, sqlite3 style) cur.execute("SELECT * FROM users WHERE email = ? AND password_hash = ?", (email, password_hash)) // SAFE (Node, pg) await db.query('SELECT * FROM users WHERE email = $1', [email]); // SAFE (PHP PDO) $stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email'); $stmt->execute(['email' => $email]); ORMs use parameters by default, but beware of "raw" query helpers where you concatenate strings yourself.
Things parameters cannot protect
Parameters work for values, not for identifiers. If you must choose a column or table name from user input, check it against an allow-list:
ALLOWED = {"name", "created_at", "price"} if sort_by not in ALLOWED: sort_by = "created_at" query = f"SELECT * FROM products ORDER BY {sort_by}" Defence in depth
- Least privilege: the app's database user should not be able to drop tables or read unrelated schemas.
- Validate input (type, length, format) as a second layer, not the only one.
- Hide detailed errors from users; log them server-side. Error messages help attackers.
- Hash passwords with bcrypt, scrypt or Argon2, never store them in plain text.
- Keep dependencies updated and use a web application firewall as an extra net, not a substitute.
How to check your own code
- Search the codebase for string concatenation or f-strings inside
execute(,query(and raw SQL helpers. - Add a test that sends
'and" OR 1=1 --to each input and expects a normal "not found" response, not an error or extra rows. - For practice in a safe, legal setting, use deliberately vulnerable labs built for learning.
Quick checklist
- Every query with user input is parameterised.
- Dynamic identifiers come from an allow-list.
- DB user has minimal permissions.
- Errors are generic for users, detailed in logs.
- Passwords are hashed with a modern algorithm.
For quick offline helpers while debugging payloads and encodings (JSON, Base64, URL), I use a browser-only toolbox: https://luxury-malabi-8a7447.netlify.app/toolbox.html
Written by Yogeshwaran Tech Tools. Corrections welcome.

