Search code examples
mysqlpdosql-in

Difficulty using an array as part of PDO "IN" query


I'm trying to query a MySQL databse using an array.

$array=array('Group1','Group2','Group3');
$inQuery=implode(",",$array);
//$inQuery='Group1'; //This returns the expected result, but is obviously not an array

$data=array($inQuery);
try {
  $STH = $this->DBH->prepare('SELECT GroupName FROM myTable WHERE GroupName IN(?)');            
  $STH->execute($data);
  /* Output results*/
}
catch(PDOException $e) { /*Panic!*/ }

I am not getting any error messages, just 0 results. Any help would be appreciated!


Solution

  • Just in case anyone else ever comes across this....

    It appeared to be an issue with escaping the imploded array.

    $array=array('Group1','Group2','Group3');
    $inQuery=implode(",",$array);
    $inQuery="'".$inQuery."'"; //Solved the issue.
    
    $data=array();
    try {
      $STH = $this->DBH->prepare('SELECT GroupName FROM myTable WHERE GroupName IN($inQuery)');            
      $STH->execute($data);
      /* Output results*/
    }
    catch(PDOException $e) { /*Panic!*/ }