views:

22

answers:

2

I have the following string...

1,2,3,4,5,6

I want to have this like

'1','2','3','4','5','6'

To use in MySQL's WHERE IN ()

Would anyone know the best way to do this?

Thanks!

+4  A: 

Use explode and implode:

 $str = "1,2,3,4,5,6";
 echo "'" . implode("','", explode(',', $str)) . "'";

 //output: '1','2','3','4','5','6'
shamittomar
In case you don't use a parametrized query: If you pass the items as string literals you should treat them as such. You either know that the input string contains only numbers, in which case OMG Ponies's critique applies, or you don't know what the string contains and you have to treat each single item with the appropriate escape function.
VolkerK
@VolkerK, I agree. Here I have just provided the strict solution to the question leaving the other `MySQL` implementations to the user.
shamittomar
A: 

You could explode your string into an array, and then join (or implode, it's an alias!) it with the quotes:

$str = '1,2,3,4,5,6';
$arr = explode(",", $str); // turns your string into array(1, 2, 3, 4, 5, 6);
$joined_arr = join("', '", $arr); // becomes 1', '2', '3', '4', '5', '6
$query = "... WHERE ... IN ('$joined_arr')"; // note the two missing quotes have been added in
Daniel Vandersluis