揮発性のメモ2

http://d.hatena.ne.jp/iww/

PDOで、INの代わりにfind_in_set関数を使う

<?
$list = array("Hana","Yuki","Ame");

$in = "?". str_repeat(",?", count($list)-1);
$sql = "select * from T_TABLE where NAME in ($in)";
$sth = $dbh->prepare($sql);

for($i=0;count($list);$i++) $sth->bindValue($i+1, $list[$i];

普通に書くとだいたいこう。 だけど、クエリーは動的に作りたくない。

<?
$list = array("Hana","Yuki","Ame");

$sql = "select * from T_TABLE where find_in_set(NAME, :NAMESET)";
$sth = $dbh->prepare($sql);

$sth->bindValue(:NAMESET, implode(",",$list);

find_in_set()を使えば、? の数なんか気にしなくてよくなる。
欠点は、引数がカンマ区切りの文字列になるので 検索対象にカンマがあれば死ぬ。
カンマが無いことを祈る。