Difficulty using an array as part of PDO “IN” query

情到浓时终转凉″ 提交于 2019-12-12 02:26:40

问题


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:


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/>';
}



回答2:


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


来源:https://stackoverflow.com/questions/6498518/difficulty-using-an-array-as-part-of-pdo-in-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!