LoginSignup
46
37

More than 5 years have passed since last update.

PDOのwhereでIN句を使う

Posted at

いつも忘れるので備忘録

PDOのwhere句でIN句を使おうとしても思ったとおりにはいかないので解決策を書いときます。


$names = array('taro', 'yuta', 'makoto');

$stmt = $pdo->prepare('
select * from user where name in (?)
');

$stmt->execute($names);
$stmt->fetchAll();

これだとうまくいきません。
where句のバインドは1:1で行うので、IN句で配列を使う場合には、配列の要素文だけ?を作らなければいけません。

そこで現状で、自分が一番簡単だと思う解決索を書いておきます。


$names = array('taro', 'yuta', 'makoto');

$inClause = substr(str_repeat(',?', count($names)), 1);

$stmt = $pdo->prepare(sptinrf('
select * from user where name in (%s)
', $inClause);

$stmt->execute($names);
$stmt->fetchAll();

IN句の中が配列の数文だけ(?,?,?)になるように作ってます。
$namesの要素文だけstr_repeat,?を書いても、最初の,は邪魔なので、substrを使って2文字目以降だけ使ってます。

他にも条件文がある場合

where句で指定するのが、IN句だけではない場合はちょっとだけ工夫する必要があります。


$names = array('taro', 'yuta', 'makoto');

$inClause = substr(str_repeat(',?', count($names)), 1);

$stmt = $pdo->prepare(sptinrf('
select * from user where age >= ? and name in (%s)
', $inClause);

$stmt->execute(array_merge(
    array(20),
    $names
);
$stmt->fetchAll();

年齢が20歳以上みたいな条件を追加した場合は、executeする時に、array_mergeでバインドする値を配列で渡して上げればOKです。

46
37
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
46
37