How to prevent SQL injection?

Posted by nikola, With 0 Comments, Category: MySQL, PHP,

Important is that any parameter in a query needs to be parameterized. It doesn't matter is your query is select, insert, update or delete kind of query, since every query can be used for injection.

Let's say that you want to have basic SELECT query, like:

SELECT `column1` FROM `table1` WHERE `column2` = 11;

You can parametarize it with code like:

$column2Value = 11;
$sql = mysqli->prepare("SELECT `column1` FROM `table1` WHERE `column2` = ?");
$sql->bind_param("s", $column2Value);
$sql->execute();

 

Conclusion:

  1. Every queries should be parameterized
  2. Every argument to query should be treated as hostile as possible no matter their source