SQL injection is an attack where a hacker types SQL code into a website's form or URL, and the website unknowingly runs that code inside its own database query. It happens when a site builds queries by pasting user input directly into SQL strings. In this guide you will see exactly how the attack works, what damage it can do, and — most importantly — how to write PHP code that stops it completely. Understanding the attack is the first step to defending your own projects against it.
What Is SQL Injection?
SQL Injection, usually shortened to SQLi, is one of the oldest and most dangerous web vulnerabilities, and it still appears in real breaches every year. Your database cannot tell the difference between SQL code you wrote and SQL code an attacker smuggles in through a form field. If your application treats everything as one long string of commands, the attacker's text becomes part of the command. That confusion between data and code is the entire problem — and also the key to fixing it. The OWASP SQL injection guide catalogues the main variants of this attack in more detail.
How the Attack Works, Step by Step
Imagine a typical login form. Behind it, many beginner projects run a query like this:
<?php
$email = $_POST['email'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE email = '$email' AND password = '$password'";
$result = mysqli_query($conn, $query);
The developer expects a normal email address. But an attacker types this into the email field instead:
admin@example.com' OR '1'='1
Because the input is pasted straight into the string, the database receives a completely different query:
SELECT * FROM users WHERE email = 'admin@example.com' OR '1'='1' AND password = ''
The condition '1'='1' is always true, so the query matches rows it should never match. The site may log the attacker in as the first user in the table — very often the admin. Notice that the attacker did not break any encryption or guess any password. The application simply executed the input as code.
What Attackers Can Do With SQL Injection
A login bypass is only the beginning. With the same trick, attackers can read data they should never see, such as customer emails, phone numbers and order history. Using UNION-based injection, they can attach a second SELECT query and pull rows from other tables, sometimes discovering the full list of tables and columns first. In worse cases they can modify or delete data — changing prices, wiping tables, or updating an account password. This is exactly why the defence matters so much, and why safe connection habits from our guide on connecting PHP with MySQL should always be paired with prepared statements.
Types of SQL Injection
Classic (In-Band) SQL Injection
The attacker sees the results of the injected query directly in the page response — for example, a search page that prints matching rows. This is the easiest type to demonstrate and the one shown in the login example above.
Blind SQL Injection
The page shows no data and no error, but it behaves slightly differently for true and false conditions — a page that loads, a different message, or a small delay using a sleep command. Attackers ask thousands of yes/no questions and rebuild the data one character at a time.
Second-Order SQL Injection
The malicious input is first stored in the database — for instance, as a username — and only executed later, when some other feature uses that stored value inside a query. It is dangerous because the input looked harmless when it was saved.
How to Prevent SQL Injection in PHP
1. Use Prepared Statements (The Real Fix)
Prepared statements separate the query structure from the data. The database receives the SQL first, with placeholders, and the values afterwards — so a value can never be mistaken for code. With PDO it looks like this:
<?php
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ? AND password = ?");
$stmt->execute([$email, $password]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
The same protection exists in MySQLi:
<?php
$stmt = $conn->prepare("SELECT * FROM users WHERE email = ? AND password = ?");
$stmt->bind_param("ss", $email, $password);
$stmt->execute();
With either version, typing ' OR '1'='1 into the form now just searches for a user whose email literally is that strange text. No match, no login, no attack.
2. Validate and Whitelist Input
Prepared statements are the main defence, but validation adds a second layer. If a field should be a number, cast it with intval(). If it should be an email, check it with filter_var($email, FILTER_VALIDATE_EMAIL). Whitelisting — accepting only input that matches an expected pattern — is far stronger than trying to block known bad words.
3. Apply the Least Privilege Principle
Your website's database user should have only the permissions it truly needs. A normal site user rarely needs permission to drop tables. If an attacker ever does get through, limited permissions limit the damage. Never run your application as the database root user.
4. Use an ORM or a Web Application Firewall
Frameworks handle much of this for you: Laravel's Eloquent ORM and Symfony's Doctrine use parameterized queries by default. A Web Application Firewall (WAF) can also block common injection patterns before they reach your code. Both are helpful extra layers, but neither replaces prepared statements in code you write yourself.
One related habit: passwords in that users table should never be stored as plain text either. Pair prepared statements with proper password hashing in PHP, so even a successful data theft does not hand attackers readable passwords.
Vulnerable Code vs Safe Code
| Point | Vulnerable | Safe |
|---|---|---|
| How the query is built | Input pasted into the SQL string | Placeholders with prepared statements |
| What input becomes | Part of the SQL command | Plain data, never code |
| ' OR '1'='1 attack | Logs the attacker in | Simply finds no matching user |
| Effort to write | Looks shorter at first | Two extra lines, protects everything |
One More Layer: Hide Your Database Errors
Detailed database error messages are a gift to attackers. An error page that prints the exact SQL problem tells them your table names, your column names and how your query is built — everything they need to aim the next attempt precisely. In development, showing errors is helpful and you should keep them visible on your own machine. On a live website, log the errors to a private file instead and show visitors a short, friendly message such as "Something went wrong, please try again." This does not fix the vulnerability by itself — only prepared statements do that — but it removes the map the attacker was reading. Treat error handling, validation and least-privilege users as supporting layers around the main defence, never as replacements for it.
Frequently Asked Questions
Is SQL injection still common today?
Yes. It has been on the OWASP list of top web risks for many years, because old code and careless string-built queries are still everywhere.
What is the single best protection against SQL injection?
Prepared statements with parameterized queries, in every query that uses user input. They make it structurally impossible for input to become SQL code.
Does escaping input with mysqli_real_escape_string() make me safe?
It helps in some cases but is easy to apply inconsistently and can be bypassed in edge cases. Prepared statements are the reliable, recommended defence.
Can SQL injection happen through a URL, not just forms?
Yes. Any input the application reads — URL parameters, cookies, form fields, even stored data — can carry an injection if it is pasted into a query.
Does using a framework remove the risk completely?
Frameworks use parameterized queries by default, but if you write raw SQL strings inside the framework, you can still create the vulnerability yourself.
Conclusion
SQL injection works because an application confuses user data with SQL code. Once you understand that, the fix is clear: prepared statements everywhere, sensible input validation, a low-privilege database user, and hashed passwords. The safe code is only a couple of lines longer than the vulnerable code — a tiny price for keeping your users' data out of an attacker's hands.
Leave a Comment