Skip to content
Home Tutorials Roadmaps Courses
Log in Join free
Tutorials MySQL SQL Injection & Prepared Statements
MySQL Intermediate FREE

SQL Injection & Prepared Statements

Lesson 1 of 16 Intermediate Interactive

SQL Injection is when malicious SQL is inserted through user input.

Prevention

  • Use prepared statements with parameterized queries
  • Validate and sanitize input
  • Use stored procedures
  • Apply least privilege principle

Syntax

MYSQL
-- VULNERABLE (never do this!)
SELECT * FROM users WHERE email = '$input';

-- SAFE: Prepared statement
PREPARE stmt FROM
    "SELECT * FROM users WHERE email = ?";
SET @email = "user@mail.com";
EXECUTE stmt USING @email;

-- In PHP (PDO)
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute(['email' => $input]);
SQL Injection Protection
SQL
-- DANGEROUS (never do this):
-- SELECT * FROM users WHERE email = "$email"

-- Use prepared statements (PDO):
-- $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
-- $stmt->execute([$email]);

-- Escape user input
SELECT * FROM users
WHERE email = "alice@example.com"
AND password = SHA2("rawsecret", 256);

-- Validate with CHECK constraints
CREATE TABLE login_attempts (
    id INT AUTO_INCREMENT PRIMARY KEY,
    email VARCHAR(150),
    IP VARCHAR(45),
    attempted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX (email, attempted_at)
);

Practice

1
Exercise

Why is concatenating user input into SQL dangerous?

Answer
Users can inject SQL commands. Always use prepared statements with parameterized queries.

Quick Quiz

1

Best protection against SQL injection?

Prepared statements separate SQL logic from data.

Interview Questions

The SQL structure is compiled first, then data is bound separately. User input is never interpreted as SQL code.