SQL Injection

The most common database attack, and how to stop it.

✍️ 3 exercises + code challenge in this lesson

SQL injection happens when user input is pasted directly into an SQL string. An attacker can type SQL code instead of normal data.

Unsafe code (PHP):

$sql = "SELECT * FROM Users WHERE Name = '" . $_GET['name'] . "'";

If someone enters ' OR '1'='1, the query becomes WHERE Name = '' OR '1'='1', which returns every user.

The fix: prepared statements

Send the query and the values separately, so input is always treated as data:

$stmt = $pdo->prepare("SELECT * FROM Users WHERE Name = ?");
$stmt->execute([$name]);

Frameworks such as Laravel (Eloquent), Django and Node ORMs use prepared statements for you.

Key Takeaways: SQL Injection

Mastering SQL Injection helps you write clean and reliable SQL code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

SQL Injection Code Example

SQL
-- What an injected query looks like: it matches every row
SELECT CustomerName FROM Customers
WHERE CustomerName = '' OR '1'='1';
Free sign-in required · Google login available

SQL Injection Practice Exercises

Check what you learned in “SQL Injection”.

/ 3 solved
Fill in the blank

Prepared statements use placeholders like this instead of pasting values.

SELECT * FROM Users WHERE Name = 
✓ Correct! Not quite. Try again.
Multiple choice

What is the best protection against SQL injection?

✓ Correct! Not quite. Try again.
Code challenge

This query is vulnerable: it returns every customer. Change the WHERE so it only matches the exact name 'Hina Books'.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services