Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I bind an array to an IN() condition?

I'm curious to know if it's possible to bind an array of values to a placeholder using PDO. The use case here is attempting to pass an array of values for use with an IN() condition.

I'd like to be able to do something like this:

<?php $ids=array(1,2,3,7,8,9); $db = new PDO(...); $stmt = $db->prepare(     'SELECT *      FROM table      WHERE id IN(:an_array)' ); $stmt->bindParam('an_array',$ids); $stmt->execute(); ?> 

And have PDO bind and quote all the values in the array.

At the moment I'm doing:

<?php $ids = array(1,2,3,7,8,9); $db = new PDO(...); foreach($ids as &$val)     $val=$db->quote($val); //iterate through array and quote $in = implode(',',$ids); //create comma separated list $stmt = $db->prepare(     'SELECT *      FROM table      WHERE id IN('.$in.')' ); $stmt->execute(); ?> 

Which certainly does the job, but just wondering if there's a built in solution I'm missing?

like image 230
Andru Avatar asked May 28 '09 11:05

Andru


People also ask

How to bind an array to an in() condition in PHP?

Syntax: SELECT <column_name(s)> FROM <table_name> WHERE <column_name> IN( value1, value2, ...); PHP implode() function: We will be using PHP predefined function implode() to deal with the array. The implode() function joins the array elements with a string.

Can we use array in where clause?

We can pass an array with the help of where IN clause. Let us first create a new table for our example. Let us now insert records.

Can I store an array in MySQL?

Although an array is one of the most common data types in the world of programming, MySQL actually doesn't support saving an array type directly. You can't create a table column of array type in MySQL. The easiest way store array type data in MySQL is to use the JSON data type.


2 Answers

You'll have to construct the query-string.

<?php $ids     = array(1, 2, 3, 7, 8, 9); $inQuery = implode(',', array_fill(0, count($ids), '?'));  $db = new PDO(...); $stmt = $db->prepare(     'SELECT *      FROM table      WHERE id IN(' . $inQuery . ')' );  // bindvalue is 1-indexed, so $k+1 foreach ($ids as $k => $id)     $stmt->bindValue(($k+1), $id);  $stmt->execute(); ?> 

Both chris (comments) and somebodyisintrouble suggested that the foreach-loop ...

(...) // bindvalue is 1-indexed, so $k+1 foreach ($ids as $k => $id)     $stmt->bindValue(($k+1), $id);  $stmt->execute(); 

... might be redundant, so the foreach loop and the $stmt->execute could be replaced by just ...

<?php    (...)   $stmt->execute($ids); 
like image 170
stefs Avatar answered Sep 25 '22 14:09

stefs


For something quick:

//$db = new PDO(...); //$ids = array(...);  $qMarks = str_repeat('?,', count($ids) - 1) . '?'; $sth = $db->prepare("SELECT * FROM myTable WHERE id IN ($qMarks)"); $sth->execute($ids); 
like image 34
uɥƃnɐʌuop Avatar answered Sep 24 '22 14:09

uɥƃnɐʌuop