Thursday 28 June 2018

Drupal: Prevent from SQL Injection

Hello All,
So today we learn how we can prevent our code from SQL injection. So first we learn what is the SQL injection and how we can prevent from this.

SQL Injection:-
It is the most common web hacking technique that might destroy your database.
So it occurs when the user ask for input. For example we want to get user detail from users table for user id 10.
so our query like be this
$uid = 10;
db_query(" SELECT  * from users where uid = $uid ");
now hacker can pass here $uid = 10 OR 1= 1
so the query will become like this
db_query(" SELECT  * from users where uid = 10 OR 1=1 ");
so it will return all rows of tables because uid = 10 may be false but 1 = 1 is always true.

So your query should be like this
db_query(" SELECT  * from users where uid = :uid ", array(':uid' => $uid));
It will prevent you from sql injection and before passing varibles into query you need to check variable type.