prevent SQL injection
Web Development

Prevent SQL Injection

How to Prevent SQL Injection Attacks?

Before we talk about how to prevent SQL injection, we have to know the impact of SQL Injection attack which is one of the most dangerous attacks on the web.

The attacker can steal your data or even worse, the whole web server can be stolen from one SQL injection vulnerability.

I wrote this post to show you how to prevent SQL injection.

If you need to know more about SQL injection itself and its types and all other stuff, you can do a simple search on google if you want.

The solution is to clean the request parameters coming from the user 

Keep in mind that the solution that I’ll share with you is not like the most solutions on the web that go to every SQL statement and clean the request variables one by one.

My solution is preventing SQL injection without messing with your CMS files.

Well, maybe someone who is using PHP would say that is easy, it is just using a function like mysql_real_escape_string or mysqli_real_escape_string.

But that works only on a single dimensional array, what about a multi-dimensional array?

Well, we need to iterate over array items recursively

So what we will do is preventing SQL injection against multidimensional array  

Solution

This code does the magic for both single and multidimensional arrays using PHP:

The PHP function used to walk through the request multidimensional array is array_walk_recursive.

Just put this code on the top of your site or header file right after connecting to the database, your file could be up.php or header.php or something similar.

Because if you use this code before the connection occurs, it will show an error because you are using mysql_real_escape_string function which needs a SQL connection.

If you are using PHP 7, you’ll notice that MySQL extension is removed, so in order to make the above code working, you need to replace the function mysql_real_escape_string with mysqli_real_escape_string.

One final thing I have to mention regarding your code, you should keep your SQL parameters on all of your pages between quotes like this:

mysql_query("select * from users where email='$email'  order by id");

Notice how the variable $email is quoted.

Without quoting your input like the above statement, SQL injection prevention won’t work.