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.