Share the ideas and thoughts, become united ...

Friday, August 13, 2010

PHP SQL Injection Prevention

The old school SQL Injection probably does not work in today's modern websites. But those who are new to PHP website development find themselves wondering around the web to learn to eliminate the SQL injection.

There is a very simple function in PHP to stop SQL injection. Consider We have a table :-
Table fake_customers
===============
id        name
--       ------
1          X
2          Y
3          Z

If we pass the ID by the get method the following code is prone to SQL injection -
$q = "select * from fake_customers where id = $id";
now what if we pass "1 and id>1" in the id parameter? Then the query will be like
$q = "select * from fake_customers where id = $id"; // select * from fake_customers where id = 1 and id>1 -- SQL injected !!!

A better approach is to use the mysql_real_escape_string() to escape the SQL escape characters.
here is the solution -
$q = sprintf("select * from fake_customers where id = %d", mysql_real_escape_string($id));

Pretty easy, isn't it?

For any suggestion or question, please leave a comment.

2 comments:

  1. ভাই,
    বাংলায় একটা jscripter বই লিখেন, আমি এখনও ভালো কুনু বাংলা টুটরিয়াল পাই নাই।

    আমার অনেক উপকার হবে

    থাঙ্ক উ

    ReplyDelete
  2. ভাই,
    বাংলায় একটা jscripter বই লিখেন, আমি এখনও ভালো কুনু বাংলা টুটরিয়াল পাই নাই।

    আমার অনেক উপকার হবে

    থাঙ্ক উ

    ReplyDelete