Incognito
Incognito

Reputation: 20765

How do I deal with an array with PDO?

Lets pretend I've got some SQL and variables such as:

$number = 5;

And my PDO sql is:

SELECT * FROM things where ID = :number

Except, number is actually an array such as:

$number = array(1,2,3);

Which doesn't work out at all for

SELECT * FROM things where ID in ( :number )

How can I accomplish this with PDO? Presently I'm looping through the array, type-casting to int, and injecting the string to the SQL before I do any PDO binding on it.

Upvotes: 1

Views: 1651

Answers (4)

Maverick
Maverick

Reputation: 2016

You can also try

$foo = conection->prepare("SELECT * FROM table WHERE id IN(:number)");

foreach ($number as $val) {
$foo->bindValue(':number', $val);
$foo->execute();
}

Hope it helps!

Upvotes: 0

Otar
Otar

Reputation: 2591

You can't bind that variable directly into statement.

Do something like this:

<?php
    $number = array(1, 2, 3);
    $number = implode(', ', $number);

    // Bind it here...

    $sql = "SELECT * FROM table WHERE id IN(:number);";

Upvotes: -1

Trott
Trott

Reputation: 70055

If you want to at least get rid of the loop, you can generate your string as such:

$numberArray = array(1,2,3);
$number = implode(",", $numberArray);

// $number is now the string "1,2,3"

Upvotes: 0

SamT
SamT

Reputation: 10610

The most common solution is to implode number (delimiting by a comma) and put the resulting string in to where in() without binding it as a param. Just be careful, you have to make sure it is safe for query, in this case.

Same thing here: Can I bind an array to an IN() condition?

Upvotes: 2

Related Questions