问题
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