0
0
SQLquery~5 mins

How SQL injection exploits queries

Choose your learning style9 modes available
Introduction
SQL injection is a way bad people trick databases to run commands they should not. It helps us understand how to keep data safe.
When learning how hackers can break into databases by changing queries.
When building apps that take user input to avoid security problems.
When testing if a website or app is safe from unwanted data access.
When teaching others about database security and safe coding.
When fixing bugs that let attackers see or change private data.
Syntax
SQL
SELECT * FROM users WHERE username = 'user_input';
This query looks for a user with the name given by 'user_input'.
If 'user_input' is not checked, attackers can add extra commands.
Examples
Normal query to find user named 'admin'.
SQL
SELECT * FROM users WHERE username = 'admin';
An attacker input that tricks the query to return all users.
SQL
SELECT * FROM users WHERE username = '' OR '1'='1'; --
An attacker tries to delete the whole users table.
SQL
SELECT * FROM users WHERE username = 'admin'; DROP TABLE users; --
Sample Program
This shows how an attacker input can change the query to return all users instead of one.
SQL
CREATE TABLE users (id INT, username VARCHAR(20));
INSERT INTO users VALUES (1, 'admin'), (2, 'guest');

-- Unsafe query with user input '' OR '1'='1
SELECT * FROM users WHERE username = '' OR '1'='1';
OutputSuccess
Important Notes
Never put user input directly into SQL queries without checking or using safe methods.
Use prepared statements or parameterized queries to stop SQL injection.
Always test your app with bad inputs to find security holes.
Summary
SQL injection tricks let attackers change what a query does.
Unsafe queries with user input can leak or destroy data.
Use safe coding practices to protect your database.