By Bryan Young
Expert Author
Article Date: 2010-08-31
What this type of attack entails is a malicious user attempting to insert their own MySQL code into your database without you knowing about it. This is done through forms. Take for example, a log in form, where you type in your username. A typical statement to verify this action would be something like this.
SELECT * FROM userinfo WHERE username = '" . $_POST['username'] . "';
This is fine as long as the user is good and types in their username as they should. The query would then look like this.
SELECT * FROM userinfo WHERE username = 'bryan';
Let's look at what happens when someone creates an injection attack and types in ' OR 1 for their username.
SELECT * FROM userinfo WHERE username = '' OR '1' = '1;
This gets ugly fast. When the database runs this statement, it sees '1' = '1' and returns all the information stored in the userinfo table. A very malicious person could even put something like this: '; DROP TABLE userinfo; --. The query now looks much scarier. Don't forget that -- is a MySQL comment.
SELECT * FROM userinfo WHERE username = ''; DROP TABLE userinfo; --';
These kinds of attacks can be devastating to your information. The easiest way to guard your data is to use a function that is built into PHP (version 4.3.0 and later), msyql_real_escape_string(). It works by taking potentially dangerous characters and preceding them with the escape character ( ). This makes them harmless characters and prevents your database from being exploited.