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!

1
  • 2
    The SQL IN clause doesn't support using a single variable for a list of values -- you'd need ? for each array value. Commented Jun 27, 2011 at 20:28

2 Answers 2

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/>';
}
Sign up to request clarification or add additional context in comments.

Comments

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!*/ }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.