Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Implode But Wrap Each Element In Quotes

Tags:

php

implode

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?

like image 313
Justin Avatar asked May 08 '12 00:05

Justin


1 Answers

Add the quotes into the implode call: (I'm assuming you meant implode)

$SQL = 'DELETE FROM elements            WHERE id IN ("' . implode('", "', $elements) . '")'; 

This produces:

DELETE FROM elements WHERE id IN ("foo", "bar", "tar", "dar") 

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 or array_walk, and escape every parameter, like so:

$elements = array(); $elements = array_map( 'mysql_real_escape_string', $elements); 
like image 73
nickb Avatar answered Oct 01 '22 11:10

nickb