I have heard that using PREPARE and EXECUTE in a SQL statement will sanitize user-supplied data into something incapable of SQL injection. Is this true?
My original query is this:
$query =
"SELECT * FROM sales_orders
WHERE ksisoldby ILIKE '".$user."'";
This is my best guess for changing it to a prepare/execute statement:
<?php
$id = $_POST['id'];
$search = $_POST['user_supplied_search_term'];
PREPARE search_query_function (varchar, varchar) AS
SELECT * FROM sales_orders
WHERE ksisoldby ILIKE '$1'";
EXECUTE search_query_function($id, $search);
?>
Is this written/invoked correctly? There are also some built in php objects (PDO) that I have read about. Should I be using those instead or in conjunction? Thanks for help on this sort of broad question.
You incorporate
prepare()andexecute()in PHP by using prepared statements, which are available when you usePDO. This extensions is responsible for creating the appropriatePREPAREandEXECUTEstatements for your database according to the database driver you have selected.Here is an example adapted from the PHP manual using
prepare()andexecute().This will take care of the parameter escaping for you and create an SQL statement similar to:
So you need to adapt the above code to include your SQL statement within the call to
prepare(), which requires you to add placeholders to where you want your parameters to be included. Then you callexecute(), which will add in the values passed to it.