Best Ways To Prevent MySQL Injection
Because internet is the biggest network in the world and everyone can be able to have access to your web site so, You as a web developer can fall in the hall of SQL Injection.. So that I will let you know how to prevent it.
Usig PHP Data Objects (PDO)
PDO is a PHP extension that work like class letting you access database more fast and secure.
$PSH = $db->prepare('SELECT * FROM table WHERE id = :id');
$PSH->execute(array(':id' => $_GET['id']));
$rows = $PSH->fetchAll();
where $db is a success PDO connection
mysql_real_escape_string()
mysql_real_escape_string() is a function that escape the unsafe character before sending the MySQL query.
$id = mysql_real_escape_string($_GET['id']);
$query = mysql_query("SELECT * FROM table where id = "' .$id. '");
preg_replace()
preg_replace() is a function that find and replace character in string. Here we will use it to find anything but numbers and remove it.
This method is good if you are selecting from MySQL using WHERE id = INT;
$id = preg_replace("/[^0-9]/","", $_GET['id']);
$query = mysql_query("SELECT * FROM table where id = "' .$id. '");
Conclusion
I used to use mysql_real_escape_string() but then I found that PDO is the best. But it’s up to you.. You can use method I wrote or you can use some class or make your own function to check input and prepare the statement for you.
Wish I helped.. Feel free to leave comments.. Just scroll down and you will find the comment box












5 Comments
Oliver
12.20.2011
This will not work:
$query = mysql_query("SELECT * FROM table where id = "' .$id. '");And int(val) should be easier here.
CH!St3R
12.20.2011
Sure int(val) is easier but it will not escape “-” (dash)
Grafik tasarim
01.08.2012
Thanks so much for sharing this!
Richard
01.24.2012
$query = mysql_query(“SELECT * FROM table where id = ‘$id’”);
As oliver said.
Also, I think you mean intval($_GET['nid']); not int(val) which puts me in the mind of Python rather than PHP.
Last time I checked, intval supports +/- as it can work with both positive and negative figures, hence the – wouldn’t matter. A DB value can of course be negative.
CH!St3R
01.24.2012
Yes, That’s right.. I’m sorry for this confusion and thanks for your comment
TUT : BEST WAYS TO PREVENT MYSQL INJECTION
01.13.2012
[...] SOURCE: http://www.webforg.com/tutorials/php/best-ways-to-prevent-mysql-injection Filed Under: PHP tutorials Tagged With: 2012, injection, mysql, php [...]
There are no trackbacks to display at this time.