PHP Prepare IN statement from array

Some of us may not know that when preparing mysql IN statement, the string inside the IN() need to be single quoted and separated by comma. Example:

SELECT Item FROM YourTable WHERE categories IN ('red', 'blue', 'green');

Unless it is a number. Otherwise double quote or no quoting the string will give you error. Example: WHERE categories IN (“red”, “blue”, “green”)

To prepare IN statement from array, the easiest way is using implode. Example:\

Array
(
	[0] =137583962056xznqi
	[1] =137583952995tqfhg
)

Simply:

$networkID = "'". implode("', '", $networkID) ."'";

Output:

'137583962056xznqi', '137583952995tqfhg'

** Note: Normal implode you will not getting the single quote on the string ”.

By Keenlio, April 14, 2014

What do you think?

Leave a Reply

Your email address will not be published. Required fields are marked *


× six = 54

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>