What is SQL injection and how do you prevent it?
Short answer: SQL Injection is a type of attack where an attacker inserts or manipulates malicious SQL code into a query, which can compromise the database.
Explain a bit more
It usually happens when user input is improperly sanitized or validated. Prevention techniques: Use Prepared Statements/Parameterized Queries: This ensures that user input is treated as data, not executable code. - Example in MySQL (using PDO in PHP) $stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username AND password = :password'); $stmt->execute(['username' => $username, 'password' => $password]); ● Input Validation: Always validate user input by checking for expected data types, lengths, and ranges. Escaping User Input: If parameters cannot be parameterized, make sure all user input is properly escaped. Least Privilege Principle: Limit database user permissions to only those necessary to perform their tasks. Web Application Firewalls (WAF): Use WAFs to detect and block SQL injection attacks.
Real-world example (ShopNest)
ShopNest’s SQL Server database stores customers, products, and orders. Good indexes and clear foreign keys keep checkout queries fast and safe.
Say this in the interview
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png