🧠 Lesson: Basic SQL Injection

1️⃣ What is SQL Injection?

SQL Injection is a type of attack where an attacker inserts malicious SQL code into a query, often through user input fields like login forms. The goal is to manipulate the database into doing something it shouldn't, like revealing sensitive data or bypassing authentication.

🚨 Why is SQL Injection Dangerous?

It can allow attackers to:

  • Steal sensitive data (e.g., emails, passwords, credit card info).
  • Delete or modify database records.
  • Bypass login systems.
  • In extreme cases, gain full control of the server.
A real-world example: In 2018, a major company lost data of 50 million users due to an SQL Injection attack!

2️⃣ Normal SQL Query

Here’s a normal login query:

SELECT * FROM users WHERE username = '$username' AND password = '$password';

If the user enters:

username: ali
password: 1234
          

The query becomes:

SELECT * FROM users WHERE username = 'ali' AND password = '1234';

3️⃣ How a Hacker Breaks It (Break Out 💣)

If an attacker inputs this as the username:

' OR 1=1 --

The query becomes:

SELECT * FROM users WHERE username = '' OR 1=1 --' AND password = '...';
  • '' ends the username field
  • OR 1=1 is always true
  • -- comments out the rest
✅ Result: attacker logs in without knowing any password!

🎯 Advanced Attack: Stealing Data

An attacker might try to steal emails with:

' UNION SELECT email, NULL FROM users --

The query becomes:

SELECT * FROM users WHERE username = '' UNION SELECT email, NULL FROM users --' AND password = '...';

This extracts all emails from the database!

4️⃣ Analogy 🤓

Think of a guard checking: "Is this Ali AND does he have password 1234?"

The hacker says:

"I'm OR 1=1"

The guard thinks: "Hmm... OR 1=1? That’s true! Go on in."

5️⃣ Ways to Prevent SQL Injection 🔐

Use these methods to secure your application:

  • Prepared Statements: Bind inputs as parameters.
  • $stmt = $db->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
    $stmt->execute([$username, $password]);
                
  • Input Sanitization: Use functions like mysqli_real_escape_string (but not as the only solution).
  • ORMs: Tools like Laravel Eloquent or Django ORM prevent SQL Injection automatically.
  • Limit Database Permissions: Use database accounts with minimal privileges.

6️⃣ Practice Code 🔬

Try this vulnerable code:

$username = $_GET['username'];
$password = $_GET['password'];

$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
echo $sql;

Access it like:

?username=' OR 1=1 --&password=123

Output:

SELECT * FROM users WHERE username = '' OR 1=1 --' AND password = '123'

Scary? Powerful? Now you see the magic (and danger) of SQLi.

🚨 Lesson: Never trust user input. Always sanitize and use prepared queries.