I'd like to safely use an array of strings within a WHERE IN
SQL statement. For example:
$myArray = array('a','b','c');
Would be converted to something like
SELECT * FROM myTable WHERE name IN ('a','b','c');
We could do this in an unsafe manner by doing something like
$in = "WHERE IN " . implode(",",$myArray);
But that is completely insecure from SQL injection.
We could use preg_replace
to strip out unwanted characters, but that might be limiting.
We could use addslashes
but I'm not confident that would be injection safe.
We could use PDO::quote
. This might work like this:
function pdoQuote($val) { global $conn; return $conn->quote($val); }
$in = "WHERE IN " . implode(",", array_map('pdoQuote',$myArray));
But the docs clearly say:
If you are using this function to build SQL statements, you are strongly recommended to use PDO::prepare() to prepare SQL statements with bound parameters instead of using PDO::quote() to interpolate user input into an SQL statement. Prepared statements with bound parameters are not only more portable, more convenient, immune to SQL injection, but are often much faster to execute than interpolated queries, as both the server and client side can cache a compiled form of the query.
Plus, it looks a bit messy, right?
We could also do something like a for loop to add the values to the query, and another for loop to bind them, but that does lead to lengthy and/or messy code.
My question: Is there a simple, safe way, that is only a single line (or so), of converting a PHP array into an SQL WHERE IN
statement, that is has no security issues?
Many thanks in advance!