douji2283 2015-05-12 08:34
浏览 94
已采纳

数组在PDO中转换为字符串

Below is my query:

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

When I replace $key = array(1,2); with $key = array($key); the query only fetches data for the first ID whereby I assume it converts the array into string.

$key also holds the value 1,2 in an array shown below:

$a=$data['sub'];

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

    $key0[]=$v;

  }

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

How do I make the PDO understand $key holds an array value and not a string?

  • 写回答

1条回答 默认 最新

  • douci1677 2015-05-12 08:52
    关注

    I solve this problem always using named placeholders. I personally don't like the ? stuff. You need a placeholder for every value of your in.

    See the sample code:

    $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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器