dppx9253 2014-07-29 09:50
浏览 78
已采纳

解决方案使用PDO将数组放入IN子句中

I've been trying the two most upvoted solutions in this thread about workaround methods to make an array work in PDO prepared statements.

Solution 1

$qMarks = str_repeat('?,', count($ids) - 1) . '?';
$sth = $db->prepare("SELECT * FROM myTable WHERE id IN ($qMarks)");
$sth->execute($ids);

Solution 2

$ids     = array(1, 2, 3, 7, 8, 9);
$inQuery = implode(',', array_fill(0, count($ids), '?'));

$db = new PDO(...);
$stmt = $db->prepare(
    'SELECT *
     FROM table
     WHERE id IN(' . $inQuery . ')'
);

But I got an error of

Invalid parameter number: mixed named and positional parameters

when applying each to my code. Does the error mean that if I use one of those solutions for $_POST["group"] (array), I can't use BindValue for $_POST["reply_name"]? Is there any solution?

Original Code (it only works if the IN Clause only has one value):

  $id_group = $_POST["group"];
  $reply_name = $_POST["reply_name"];

  foreach($id_group as $key => $id)
  {
    $ins[] = "".($id)."";
  }

  $in = implode(",",$ins);

  $sql = "SELECT a.name from `reviews` a 
           INNER JOIN `users` b 
            ON a.id = b.id  
           WHERE a.reply_name = :reply_name 
           AND a.id_group IN (:id_group) 
           ORDER BY a.id_group";

  $users = $dbh->prepare($sql);
  $users->bindValue(':reply_name',$reply_name);
  $users->bindValue(':id_group',$in);
  $users->execute();

  foreach($users as $row)
  {
    echo $row["name"];
  }
  • 写回答

1条回答 默认 最新

  • dongluojiao6322 2014-07-29 10:02
    关注

    You cannot use :namedParameters and ? placeholders at the same time, as the error says. It's either or, never mixed. You'll either have to convert all your placeholders to ? and bind all your parameters using positional offsets:

    $users->bindValue(1, $reply_name);
    ...
    $i = 3;
    foreach ($ids as $id) {
        $users->bindValue($i++, $id);
    }
    
    // or
    
    $users->execute(array_merge(array($reply_name, $in), $ids));
    

    or you make named placeholders for each id:

    $placeholders = array_map(function ($num) { return ":id$num"; }, range(1, count($ids)));
    $stmt = $pdo->prepare(sprintf('SELECT ... IN (%s)', join(', ', $placeholders)));
    // .. bind :id1, :id2 etc. similar to above example
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?