K
K
Klein Maximus2016-12-09 20:51:56
PHP
Klein Maximus, 2016-12-09 20:51:56

How to bind an array of values ​​in an IN condition when using PDO?

<?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();
?>

I really don't want to do implode(..., $ids) - I'll have to fiddle with quotes and all the profit from preparing the request essentially disappears :(

Answer the question

In order to leave comments, you need to log in

3 answer(s)
F
FanatPHP, 2016-12-13
@kleinmaximus

Classic solution:

<?php
$ids=array(1,2,3,7,8,9);
$in  = str_repeat('?,', count($arr) - 1) . '?';
$stmt = $db->prepare('SELECT * FROM table  WHERE id IN($in)');
$stmt->execute($ids);
Not too pretty, but safe.

E
eudj1n, 2016-12-09
@eudj1n

Unfortunately, no way, you have to convert the array to a string.

R
Rsa97, 2016-12-09
@Rsa97

You can use FIND_IN_SET instead of IN, but indexes won't work.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question