2

I have SQL procedure in which I'm using an IN statment. It goes like this:

SELECT * FROM costumers WHERE id IN('1','2','12','14')

What I need to do is pass the values in to the IN statment as parameter which is an array in php, rather than hard-coded. How can I do that?

1
  • Simply replace your single quote encapsulates variables with a reference to the array key you want to use I.e. $myarray[0] Commented Sep 10, 2014 at 14:01

6 Answers 6

3

You can implode on this case:

$array = array('1','2','12','14');
$ids = "'".implode("','", $array) . "'";
$sql = "SELECT * FROM `costumers` WHERE `id` IN($ids)";
echo $sql;
// SELECT * FROM `costumers` WHERE `id` IN('1','2','12','14')

or if you do not want any quotes:

$ids = implode(",", $array);
Sign up to request clarification or add additional context in comments.

1 Comment

this helped, thank you. Had to use ids array like this though: ".$ids."
1

You can use PHP function Implode

$array = array("1","2","12","14");

$query = "SELECT * FROM costumers WHERE id IN(".implode(', ',$array).")"

Comments

1

implode() is the right function, but you also must pay attention to the type of the data.

If the field is numeric, it is simple:

$values = array(1. 2, 5);
$queryPattern = 'SELECT * FROM costumers WHERE id IN(%s)';
$query = sprintf($queryPattern, implode(', ',$values));

But if it's a string, you must play with single and double quotes:

$values = array("foo","bar","baz");
$queryPattern = 'SELECT * FROM costumers WHERE id IN("%s")';
$query = sprintf($queryPattern, implode('", "',$values));

Comments

0

This should do the trick

$array = array('1','2','12','14');

SELECT * FROM `costumers` WHERE `id` IN('{$array}');

Comments

0

Try imploding the php into an array, and then interpolating that string into the SQL statement:

$arr = array('foo', 'bar', 'baz');
$string = implode(", ", $arr);

SELECT * FROM customers WHERE id in ($string);

Comments

0

use PHP's join function to join the values of an array.

$arr = array(1,2,12,14);

$sql = "SELECT * FROM costumers WHERE id IN(" . join($arr, ',') . ")";

3 Comments

join and implode are actually the same, I prefer join, but others here seem to prefer implode. (What's the difference? -[stackoverflow.com/questions/17914008/…)
I prefer implode to easily distinguish it from SQL JOIN and it is also easier to recognize as the complementary function of explode.
A valid reason @rink.attendant.6. The reason for my preference is just that join is the more common name for this function in other languages (SQL excluded), like C#, Perl, Python, Java, Javascript, etc. -- implode/explode is almost unique to PHP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.