-1

Below is My Array

Array ( [0] => test [1] => jaz )

I want to pass this array using IN Function in mysql like that

$q = "select * from claimant where org IN (Array)";

but i need to change my INDEXED ARRAY to simple Array like (1,2,3,4) how i can change array and pass it to mysql IN condition Thanks in Advance

2 Answers2

1

If your array will not contain values like quotes ( " or ') then you can something like this:

$array = array(1=>'test', 2=>'jaz');
$inClause = '"' . implode('","', $array) . '"';
$q = "select * from claimant where org IN ({$inClause})";

Important notes

Even though this code snippet will work for you, if the values in array are comming from user (user makes input in some kind of form or something), then your SQL query will be wurnerable to the SQL Injection attack. That means someone can delete your database, or take your data.

MrD
  • 2,423
  • 3
  • 33
  • 57
0

Convert the array into a string first. You cannot directly use an array in a String.

Use this code to convert the array into a string:

$array = array(0 => 'test',1 =>'jaz');

$str = "";
foreach($array as $value) $str .= ",'$value'";
$str = substr($str,1);

Then you can change your SQL to look like this:

$q = "select * from claimant where org IN ($str)";

That should generate an SQL string like this: select * from claimant where org IN ('test','jaz')

Jacques Koekemoer
  • 1,378
  • 5
  • 25
  • 50
  • Yuck, foreach is an ugly solution. implode was designed for this purpose. – Ultimater Sep 09 '15 at 08:50
  • Yes I agree foreach is not a good solution but how else would you escape the values. This is perfect because now it also gives the developer the chance to manipulate and change the values before processing them – Jacques Koekemoer Sep 09 '15 at 08:53
  • True, but if we're gonna attempt to do things right for any problematic strings, I'd sooner take advantage of parameter binding: http://stackoverflow.com/questions/14960621/mysql-bind-param-with-in – Ultimater Sep 09 '15 at 09:10