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?
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.
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.
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.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With