Protecting your PHP/MySQL queries from SQL Injection

The following method was described as a safe way to execute mysql queries.

// This is a vulnerable query.
$query = “SELECT * FROM products WHERE name=’$productname'”;
mysql_query($query);

// This just uses mysql_escape_string
$query = sprintf(“SELECT * FROM products WHERE name=’%s'”,
mysql_real_escape_string($productname));
mysql_query($query);

The above query will work, with select and insert statements, but will not work with statements such as: LIKE, GRANT, or REVOKE. The following query is a more secure way of preventing SQL injection attacks.

// This query is more secure
$query = sprintf(“SELECT * FROM products WHERE name=’%s'”,
addcslashes(mysql_real_escape_string($productname),’%_’));
mysql_query($query);

Leave a comment

Your email address will not be published. Required fields are marked *