SQL Injection

SQL Injection Explained for Beginners: How It Works and How to Prevent It

SQL Injection (SQLi) is one of the oldest and still most common web application vulnerabilities. It happens when an application takes user input and inserts it directly into a database query without properly validating or sanitizing it first. If an attacker can control part of that query, they can control what the database does — read data they shouldn’t see, bypass logins, or in the worst cases modify or delete data entirely.

How It Works

Imagine a login form that builds a query like this behind the scenes:

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

If the application just drops raw user input into that string, an attacker can type something like ' OR '1'='1 into the username field. The query becomes:

SELECT * FROM users WHERE username = '' OR '1'='1' AND password = '...';

Since '1'='1' is always true, the database can return a valid user row without the attacker knowing any real password — logging them in as someone else.

What Attackers Can Actually Do With It

  • Bypass authentication entirely
  • Extract sensitive data (emails, password hashes, personal information)
  • Modify or delete records in the database
  • In some database configurations, read files from the server or even execute OS commands

How Defenders Prevent It

The fix is not “filter bad characters” — that approach is fragile and attackers routinely bypass blacklists. The real fix is to never let user input become part of the query structure in the first place:

  • Parameterized queries / prepared statements — the database treats user input strictly as data, never as part of the SQL command itself
  • ORMs (like Sequelize, Eloquent, Hibernate) that generate parameterized queries by default, reducing the chance of a developer writing raw string-concatenated SQL
  • Least-privilege database accounts — the application’s database user shouldn’t have permissions it never needs, limiting the blast radius if SQLi does occur
  • Input validation as a secondary layer — good practice, but never a substitute for parameterized queries
    Key takeaway: SQL Injection exists because of trust — the application trusted user input to be safe SQL. The fix is architectural (parameterized queries), not just filtering — that’s what makes SQLi so persistently common even decades after it was first documented.
 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top