Assume I have an array:
$elements = array('foo', 'bar', 'tar', 'dar');
Then I want to build up a DELETE IN
SQL query:
$SQL = "DELETE FROM elements
WHERE id IN ('" . implode(',', $elements) . "')";
The problem is that the ids in the elements array aren't quoted each individually. I.E the query looks like:
$SQL = "DELETE FROM elements
WHERE id IN ('foo,bar,tar,dar');
What's the best, most elegants way to fix this?
You can use
array_walk
to iterate all the elements in side the array passing the reference to the element and add the quotes in the following way.Add the quotes into the
implode
call: (I'm assuming you meantimplode
)This produces:
The best way to prevent against SQL injection is to make sure your elements are properly escaped.
An easy thing to do that should work (but I haven't tested it) is to use either
array_map
orarray_walk
, and escape every parameter, like so:Just to add to the top answer a bit here, even if you are using MySQLi it is possible to call real_escape_string using array_map by using the object method
callable
form. Here is an example, assuming$conn
is your MySQLi connection:Note that the first parameter of array_map is an array with the object followed by the method name. This is the same as executing the following for each item in the array:
You can run a simple array_map() function to wrap the strings in quotes and then wrap that around the implode() to add the commas: