Search code examples
phpsqlprepared-statementsql-injectionsanitization

Difference between POST Sanitation and Prepared statements in PHP


I always used the PDO prepared statements to prevent SQL injection.

$params = array(':param' => 'value');

But now someone told me that I should use POST sanitation to prevent SQL injection.

$_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

Now my question is why do I need to use POST sanitation when I already use prepared statements for my queries?

So after all my queries could be not secure against SQL injection after all?


Solution

  • Prepared statements protect you from SQL injection, but do not ensure data is valid.

    But beside a possible SQL injection you want your data as valid and clean as possible.

    Say, someone gives an email address in a form, but it isn't one, you should not store it before being validated. Same for any other data type.

    Doing some things like trimming spaces makes data smaller. Smaller data benefits also by faster results and indexing.

    The safest way to prevent SQL injections is using PDO and prepared statements.

    You should also verify any input before inserted, because user data can be evil. Many forms are spammed by bots, for example.