数组在PDO

时间:2015-05-12 08:34:29

标签: php mysql arrays pdo

以下是我的询问:

$key = array(1,2);
$in = join(',', array_fill(0, count($key), '?'));
$statement = $pdo->prepare("SELECT * FROM posts WHERE posts.subid IN (".$in.") AND posts.pricing=?  AND posts.Poscode=? ORDER BY posts.Poscode DESC LIMIT 60");
$result = array_merge($key, array($rate,$postcode));
$statement->execute($result);

当我用$key = array(1,2);替换$key = array($key);时,查询只获取第一个ID的数据,我假设它将数组转换为字符串。

$key还在下面显示的数组中保存值1,2:

$a=$data['sub'];

$key0=array();
foreach($a as $v=>$k) 
  {

    $key0[]=$v;

  }

 $key2=implode(',',$key0);
 $key = array($key2);

如何让PDO理解$key保存数组值而不是字符串?

1 个答案:

答案 0 :(得分:1)

我总是使用命名占位符来解决这个问题。我个人不喜欢?的东西。您需要一个占位符来表示您的每个值。

参见示例代码:

$key = array(1,2);
$pricing = "somePricing";
$postcode = "somePostcode";


$bindings = array();
$bindings[] = array(":pricing", $pricing, PDO::PARAM_STR);
$bindings[] = array(":postcode", $postcode, PDO::PARAM_STR);

$key_placeholders = array();
foreach($key as $k => $v) {
    $placeholder = ":subid".$k;
    $bindings[] = array($placeholder, $v, PDO::PARAM_INT);
    $key_placeholders[] = $placeholder;
}

$sql = "SELECT * FROM posts "
        . "WHERE posts.subid IN (". implode(",",$key_placeholders).") "
        . "AND posts.pricing=:pricing  "
        . "AND posts.Poscode=:postcode "
        . "ORDER BY posts.Poscode "
        . "DESC LIMIT 60";

$statement = $pdo->prepare($sql);
foreach($bindings as $b) {
    $statement->bindValue($b[0],$b[1],$b[2]);
}
$statement->execute();