PDO bind value list for IN statement  [ 926 views ]

Goal: pass value list to IN statement

The PDO variable binding is easy until you want to use an IN statement like

   SELECT *
     FROM table
    WHERE id IN (1,2,3,4)

with PDO

$sql = <<<EOT
  SELECT *
    FROM table
   WHERE id IN (?)
EOT;

after the binding this statement is not working because in the background the select statement will be like this:

   SELECT *
     FROM table
    WHERE id IN ('1,2,3,4')

Luckily the mysql knows the following tricky form

   SELECT *
     FROM table
    WHERE find_in_set(cast(ID as char), '1,2,3,4')

and the bindable form is the following

$sql = <<<EOT
  SELECT *
    FROM table
   WHERE find_in_set(cast(ID as char), ? )
EOT;

Job done. Enjoy the result…

#sidebar a { color:#fff; } #sidebar ul ul li { color: #DEF585; } #sidebar h2 { color: #fff; } #sidebar ul p, #sidebar ul select { color: #BEDDBE; } #backfly { background: url(images/golfBallWallPaper.jpg) left bottom fixed repeat-x #65a51d; }