Aug 7, 2011

How To Stop SQL Injections in PHP | Best Way To Stop MYSQL Injections

Now a days hacking has became a hobby for young generations, people start hacking and destroy the websites just for the sake of fun or business, amongst all of them SQL injections also known as DdoS is becoming very famous. But what is SQL injections? Suppose you have a website or a forum where a user can find something for him/her. That person searches the keyword by using Search option, this is where SQL injections start, a normal search is ok, say about a server can handle couple of searches at a time, but what if same website opened in 100 windows and at the same time 100 searches or more then that are made, then your server will go down and hackers can easily break the firewall and hack your website data from the server.

This is very common now a days, so to get rid of this the php code of search should be changed.

Default Search Code:

[php]
// connect to the mysql database

$unsafe_var = $_POST["keyword"];

mysql_query("SELECT * FROM table1 where keyword='". <code>$unsafe_var</code> ."'");

// disconnect from the mysql database
[/php]

The best way is to use prepared statements
Something Like this

[php]
$preparedStatement = $db->prepare('SELECT * FROM employees WHERE name = :name');

$preparedStatement->execute(array(':name' => $name));

$rows = $preparedStatement->fetchAll();

[/php]

This is the best way to get rid of SQL Injections.
In the above SQL statements you pass to prepare is parsed and compiled by the database server. By specifying parameters (:name) we are telling the database engine where the filter should be on. Then when we call execute the prepared statement is combined with the parameter values we specify.

Simple and secure

So always use safe coding, after all coding is fun not destruction.

Happy Coding :)

3 comments :

  1. PHP Frameworks have solved this issue. I am using CodeIgniter PHP Framework and executing SQL queries are something like this:

    $this->db->select('field1, field2)
    ->from('table')
    ->where('field', $this->input->post('fieldname')
    ->get()

    Now... we have double filtration: DB and INPUT classes.

    ReplyDelete
  2. @Dalibor Sojic thanks for sharing the code, and yes framework like cake, yii, zend, codeigniter etc helps to be secured, but many people use normal PHP for their websites, so they will need to do something like this

    ReplyDelete
  3. There is any option to bind table name and columns fields also dynamic....??????/

    plz help
    pradeeprai87@gmail.com

    ReplyDelete