How can I prevent SQL injection in PHP?

If user input is inserted without modification into an SQL query, then the application becomes vulnerable to SQL injection, like in the following example:

$unsafe_variable = $_POST['user_input']; 

mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')");

That’s because the user can input something like value'); DROP TABLE table;--, and the query becomes:

INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--')

What can be done to prevent this from happening?

What happens if you prepare the statement?

1 Like

As @sibtertius says, preparing the query properly is the correct solution. Note that simply preparing the existing query is not sufficient, you need to actually use proper parameterization.

Also, mysql_ was deprecated in PHP 5.5, and removed from PHP in 7.0. You at the very least should be using mysqli_ , if not PDO.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.