0

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!

Matt
  • 7,022
  • 16
  • 53
  • 66
  • 2
    The SQL `IN` clause doesn't support using a single variable for a list of values -- you'd need `?` for each array value. – OMG Ponies Jun 27 '11 at 20:28

2 Answers2

1

You could try this way - not tested - :

// To fetch your array data
$array=array('Group1','Group2','Group3');
try {
  $STH = $this->DBH->prepare("SELECT GroupName FROM myTable WHERE GroupName IN (?)");            
  $STH->execute($array);
  while($lines=$STH->fetch($this->DBH->FETCH_OBJ))
{
        echo $lines->GroupName.'<br />';
}

}
catch(PDOException $e) { 
/*Panic!*/ 
echo 'ERR: ' .$e->getMessage().'<br/>';
}
hornetbzz
  • 9,188
  • 5
  • 36
  • 53
0

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!*/ }
Matt
  • 7,022
  • 16
  • 53
  • 66