SQL injections in 2026: how they work and how to get AI to write truly safe code
Next step
Open the bot or continue inside this section.
Article -> plan in AI
Paste this article URL into any AI and get an implementation plan for your project.
Read this article: https://vibecode.morecil.ru/en/bezopasnost/sql-inejsii/
Work in my current project context.
Create an implementation plan for this stack:
1) what to change
2) which files to edit
3) risks and typical mistakes
4) how to verify everything works
If there are options, provide "quick" and "production-ready". How to use
- Copy this prompt and send it to your AI chat.
- Attach your project or open the repository folder in the AI tool.
- Ask for file-level changes, risks, and a quick verification checklist.
SQL injection remains one of the most dangerous yet primitive vulnerabilities in web development. It doesn’t require “magic”—only a careless line of code, where user input goes directly into a SQL query. The consequences can range from a data breach to a total database destruction.
Despite the development of frameworks and ORM, the problem has not gone away. The reason is simple: the speed of development has increased, especially with the advent of AI. Models generate code quickly, but without explicit security requirements, they easily create vulnerable designs.
In this article, we will analyze exactly how SQL injections work, what types of attacks exist, how they are detected in practice and, most importantly, how to build a system in which even AI-generated code will be initially secure.
1. What is SQL Injection (in simple words)
Imagine you write a request to the database:
SELECT * FROM users WHERE login = 'введённый_логин';
The user enters instead of the login:
admin' OR '1'='1
The request becomes:
SELECT * FROM users WHERE login = 'admin' OR '1'='1';
The database gives all users. Welcome to the classic SQL injection.
It's not a database bug. This is a bug of your code that allowed the user to “interfere” with the SQL query.
The real consequences:
- Leaked millions of passwords (think Yahoo, LinkedIn, Sony).
- Complete removal of tables (
DROP TABLE users). - Read server files (
LOAD_FILE('/etc/passwd')). - Server capture via xp cmdshell (in old MSSQL).
Even in 2026, OWASP puts Injection at No. 1 in the Top 10.
2. What it looks like in practice (examples of vulnerable code)
** Bad code:**
Python + psycopg2
#ОП Dangerous!
query = f "SELECT * FROM users WHERE email = '{user email}'"
cur.execute(query)
Node.js
It's dangerous!
const query = `SELECT * FROM bots WHERE token = '${token}'`;
PHP
// ❌ Классика 2010-х
$sql = "SELECT * FROM users WHERE id = " . $_GET['id'];
The hacker in the e-mail field writes: ' OR '1'='1 - and done.
3. Types of SQL injections
- Classic (Error-based) - the database curses the error and gives the data.
- Union-based -
UNION SELECT password FROM users(most popular). - Blind (Boolean/Time-based) -
AND (SELECT 1)=1orAND SLEEP(5)queries. - *Out-of-band – the data goes to the hacker’s server via DNS.
- **Second-order ** Injection is triggered later (e.g., when stored in the database and then read).
4. How hackers find vulnerability
The most popular tool is sqlmap.
Please put it in your hands (so he can set it up for you):
Write a step-by-step plan for installing and running sqlmap against my test endpoint /login?email= on the locale. Use --risk=3 --level=5 --batch. Show me the login form test command.
Run and you'll see the red lines "[CRITICAL] parameter 'email' is vulnerable.".
5. Main Protection: Parameterized Requests (Prepared Statements)
This is the only 100% way to shut down SQL injections at the code level.
How it works:** The database first receives the “template” of the request, then separately – the data. Data never becomes code.
6. Ready-made solutions
Option A - ORM (recommended for beginners)
- Prisma (Node.js/TypeScript) is a dream come true.
- SQLAlchemy 2.0 (Python) - with async.
- *Drizzle ORM (TypeScript) is lightweight and fast.
- GORM (Go) - in case you happen to.
Prompt for Claude/GPT (Universal):
Write the full user authorization code in the Telegram bot in Python + aiogram 3 + SQLAlchemy 2.0 + asyncpg (PostgreSQL/Supabase).
Use parameterized queries (not f-lines!).
Add email validation through Pydantic.
Add a rate-limit of 5 attempts per minute.
Make the code as safe as possible and with comments for the beginner.
Option B - manual prepared statements
Python + psycopg2 (Supabase)
cur.execute(
"SELECT * FROM users WHERE email = %s AND password = %s",
(email, hashed_password)
)
Node.js + pg
const { rows } = await pool.query(
'SELECT * FROM users WHERE email = $1',
[email]
);
PHP + PDO
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$email]);
7. Additional levels of protection (defense in depth)
** Validation and sanitization of input**
- Regulars + whitelist.
- Zod/Pydantic/Joi.
The Principle of Least Privileges
- Create a separate database user ONLY with SELECT/INSERT/UPDATE rights to the desired tables.
- Never use
postgresorrootin the app.
**Web Application Firewall (WAF) **
- Cloudflare WAF (free up to 100k requests).
- ModSecurity + OWASP CRS.
- Supabase has built-in protection.
Stored procedures (with parameters!)
*ORM + Prepared Statements = It is almost impossible to be wrong.
8. How to Ask AI to Write Safe Code
Universal promt template:
Write the code for [function, for example: user registration].
Mandatory requirements:
Use only parameterized queries / ORM
Never concatenate strings in SQL
- Validation through [Zod/Pydantic]
- Rate limiting
Hashing passwords via bcrypt/argon2
- Comments "// SECURITY:" for each protective measure
Protection against SQLi, XSS, CSRF
9. Checklist before depletion
- Are all SQL queries parameterized?
- Does the user have minimum rights?
- Validation + Sanitation at all entrances?
- Is the sqlmap test running?
- WAF on?
- Logging suspicious requests?
- Regular dependency updates (
npm audit,pip-audit)?
10. What to do if you have already been hacked
- Turn off the app.
- Change all passwords and tokens.
- Restore it from a clean backup.
- Do a code audit.
- Add all protections above.
- Notify users (by law).
Conclusion
SQL injection is not a “complex hacking thing.” This is an error that can be closed with one correct line of code.
Now, in the age of AI, you can write code faster than anyone else — but only if you teach AI how to write *safely.