mysql_injection

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 :)

Related Posts

subscribe1

Create Your Own Subscription System (Part1)

css3button

How to Create a Beautiful Button Using CSS3

OOP

Getting Started With Object-oriented Programming (OOP)

5 Comments

  1. Oliver

    12.20.2011

    Reply

    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

      Reply

      Sure int(val) is easier but it will not escape “-” (dash)

  2. Grafik tasarim

    01.08.2012

    Reply

    Thanks so much for sharing this!

  3. Richard

    01.24.2012

    Reply

    $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

      Reply

      Yes, That’s right.. I’m sorry for this confusion and thanks for your comment :)

Leave a Reply