SQL Injection is a security vulnerability that lets an attacker manipulate the SQL queries your application sends to the database.
It happens when user input is directly added to SQL queries without proper sanitization or prepared statements.
function login(username, password) {
const query = `
SELECT * FROM users
WHERE username = '${username}'
AND password = '${password}'
`;
return database.exec(query);
}
If we set username
to:
' OR 1=1 --
The final SQL becomes:
SELECT * FROM users WHERE username = '' OR 1=1 --' AND password = ''
This query will always return true
, give a list of all users, and the app will
probably pick the first one.
This allows us to easily bypass the login.
Use Prepared Statements (Parameterized Queries)
This is always the first thing you should do
Use ORM Libraries
Frameworks like Django and Prisma generate safe queries by default
Validate & Sanitize Input
Check types, lengths, formats, and never trust the user
Here’s a vulnerable login form demo. You can enter your own inputs and see the generated SQL query, then try to break it with SQL injection.
Find this post helpful? Subscribe and get notified when I post something new!