What is SQL Injection and how to make your PHP site free from SQL Injection hacking


Read {count} times since 2020

SQL Injection (SQLi) is a very dangerous thing that a hacker can do to your site. This happens mostly in SQL queries. Let me make you understand this in a simple way. Suppose you’re SQL query code is this:

$user=$_GET[‘user’];
$sql=mysql_query("SELECT * FROM users WHERE user='".$user."‘");

It’s a normal code. BUT it is a very easy method for hacker to easily destroy your database.
The user ID is getting from a GET request. If the file’s name (where the request is going) is user.php. The URL may be like this:

http://example.com/user.php?user=subin

and the SQL query will be :

SELECT * FROM users WHERE user=’subin

The file will print out user information and other stuffs. But what if the hacker put on more values in the user variable in the URL. Suppose like this:

http://example.com/user.php?user=subin’;DROP TABLE users;SELECT * FROM user WHERE user=’otherguy

OR like this:

http://example.com/user.php?user=subin";DROP TABLE users;SELECT * FROM user WHERE user=’otherguy

and the SQL query will be:

SELECT * FROM users WHERE user=’subin‘;DROP TABLE users;SELECT * FROM user WHERE user=’otherguy’;

You know what will happen. Yes that’s right. The table ‘users’ will be deleted and your entire table is lost. The hacker can also delete the database if he/she wants. So now you understand what is SQL Injection

How to make your PHP site free from SQL Injection hacking

This method is real simple. All you have to do is add mysql_real_escape_string() function in variables in an  SQL query. Example:

$user=mysql_real_escape_string($_GET[‘user’]);
$sql=mysql_query("SELECT * FROM users WHERE user='".$user."‘");

Enjoy un-hackable site.