Home Fun Games Blog CDCRIFD CDRD Utilities About Settings

Data Sanitization/SQL Injection

Data sanitization is extremely important. It prevents against common attack techniques such as SQLi (SQL Injection). It is basically making sure that users don't close the string and execute their own commands.


Randall Munroe has a great comic on this (I used his because he is cool & I read his books. You should, too).

In this case, the SQL table name is "Students". A valid SQL command for adding Robert would be:

INSERT INTO (firstname) VALUES ('Robert');

Now if a user with malicious intent inserts Robert'); DROP TABLE Students; -- into the "Add Student" box, the command would be:

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

-- example is treated as a comment in SQL. A semicolon signifies the end of a command. So the final set of commands would be:

INSERT INTO (firstname) VALUES ('Robert');

would insert 'Robert' into the "Students" table under "firstname" and

DROP TABLE Students;

would effectively delete the "Students" table.

Escaping Special Characters

Escaping special characters is a useful solution to this problem and many others. For example, alert("And then Bob said, "Hey there"."); would trigger an error because the browser would see it as alert("And then Bob said, "Hey there".");. The browser would be confused as to what the second phrase (marked in red) is. Put a backslash behind special characters. For example, use alert("And then Bob said, \"Hey there\".");. The escaped characters (marked with mint green) do not interfere with the quotations of the string.