How does the SQL injection from the “Bobby Tables” XKCD comic work?

Just looking at:


What does this SQL do:


I know both ' and -- are for comments, but doesn't the word DROP get commented as well since it is part of the same line?


It drops the students table.

The original code in the school's program probably looks something like

q = "INSERT INTO Students VALUES ('" + FNMName.Text + "', " + LName.Text + ")";

This is the naive way to add text input into a query, and is very bad, as you will see.

After the values from the first name, middle name textbox FNMName.Text (which is Robert'); DROP TABLE STUDENTS; --) and the last name textbox LName.Text (let's call it Derper) are concatenated with the rest of the query, the result is now actually two queries separated by the statement terminator (semicolon). The second query has been injected into the first. When the code executes this query against the database, it will look like this

INSERT INTO Students VALUES ('Robert'); DROP TABLE Students; --', 'Derper')

which, in plain English, roughly translates to the two queries:

Add a new record to the Students table with a Name value of 'Robert'


Delete the Students table

Everything past the second query is marked as a comment: --', 'Derper')

The ' in the student's name is not a comment, it's the closing string delimiter. Since the student's name is a string, it's needed syntactically to complete the hypothetical query. Injection attacks only work when the SQL query they inject results in good SQL (good being very relative in this case).

Edited again as per dan04's astute comment

Need Your Help

Android: How to direct to another page?

java android xml eclipse

Hey awesome coding geniuses! I'm a student doing my final year project and i need some help. I hope you coding geniuses can help!

How to target a file (a path to it) in Java/JavaFX

file path media javafx-2

It might be a simple one, but i can't seem to get it to work. I am making a video player in JavaFX but I don't know how to target the file that is going to be played (I don't know the correct synta...