Helenp Helenp - 1 year ago 55
MySQL Question

Array in cookie, access with pdo query

I am working with a script not mine, and I have an array of id's in a cookie.
When I print the cookie array it prints like this:

["39","580"]
. I need to access
id
39
and
580
.

I have tried everything I know to use this in a query like this:

$queryordenar = $db->prepare("SELECT id FROM property
WHERE id IN (:list) ORDER BY price ASC");
$queryordenar->execute(array(
'list' => $array
));


Thanks

Answer Source

You can't pass an array as a parameter. You need to explode the array, pass in a ? for every value, and then bind the correct value to each placeholder:

$bindPlaceholders = [];
foreach ($array as $val) {
    $bindPlaceholders[] = "?";
}
$bindString = "(".implode(",", $bindPlaceholders).")";
$queryordenar = $db->prepare("SELECT id FROM property WHERE id IN ".$bindString." ORDER BY price ASC");
foreach ($array as $i => $val) {
    $queryordenar->bindValue($i + 1, $val); // binding starts at 1
}
$queryordenar->execute();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download