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 :)
PHP Frameworks have solved this issue. I am using CodeIgniter PHP Framework and executing SQL queries are something like this:
ReplyDelete$this->db->select('field1, field2)
->from('table')
->where('field', $this->input->post('fieldname')
->get()
Now... we have double filtration: DB and INPUT classes.
@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
ReplyDeleteThere is any option to bind table name and columns fields also dynamic....??????/
ReplyDeleteplz help
pradeeprai87@gmail.com