You might have came across the term SQLi (SQL injection). SQLi is a code injection technique which can be used access database’s information without anyone’s permission. Or placement of malicious code in SQL statements, via web page input.

The most common practices of executing SQLi code is by adding a quote character () in a vulnerable parameter. If the SQLi is successful the web-page crashes with an unexpected error:

An error occurred: PG::SyntaxError: ERROR: unterminated quoted string at or near “‘ password ” limit 1″ LINE 1: …om users where email = ‘[email protected]’ and password = ‘password” … ^ : select * from users where email = ‘ [email protected] ‘ and password = ‘ password” limit 1. Unable to login this user due to unexpected error.

bank crash – basics

Knowing only how to code does not make you a good programmer. And having only a “working program” does not make it the best. The problem with most programmers is that they don’t understand or don’t want to understand the concept of security/hacking at all. I have said this before and I will say it again; learning every high or low level language without being able to make it secure is not enough!

Consider this, John writes a PHP code and stores the $input variable as following:

$input = $_GET[“user-input”];

mysql_query(“INSERT INTO table (column) VALUES (‘” . $input . “‘)”);

Since the script is taking input from user and if someone added a quote character, the value of $input will be the user input followed by a preceding quote and hence it will generate an SQL error. For example: https://www.johnswebsite.com/comment.php?user-input=StringWithQuote’

How should you then take an input from a user?

It depends. If you take the same code above, consider escaping the $input variable. For PHP, there is already a function present called mysql_real_escape_string which will do the trick.

$input = $_GET[“user-input”];

$safe_variable = mysql_real_escape_string($input);

mysql_query(“INSERT INTO table (column) VALUES (‘” . $safe_variable . “‘)”);

What is actually happening in the Background?

The function mysql_real_escape_string adds an escape character, the backslash, \, before certain dangerous characters in a string is passed. So if a user entered an input as “DangerousString’” the function will pass the string as “DangerousString\’” hence escaping the quote character or any other character which can potentially cause an SQL injection.

Note: Unless magic_quotes is off, PHP runs addslashes() function on all GET, POST and COOKIE data by default.

This does not necessarily means that by adding only an escape function on strings it will make your program 100% hack-proof. There are hundreds of ways around SQL injection which I will be discussing further. I want you to understand how important the topic of security/hacking is, in terms of programming.

Have something to say about this article? Comment below or share it with us on Facebook, Twitter or our LinkedIn Group.