简体   繁体   中英

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.

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?

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"

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!

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);";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM