PDO and SQL IN statements [duplicate]

孤者浪人 提交于 2019-12-24 10:59:48

问题


Im using a sequel for search like this using PDOs

$states = "'SC','SD'";  
$sql = "select * from mytable where states in (:states)";  
$params = array(':states'=>$states); 

and I use my function

$result = $this->selectArrayAssoc($sql, $params);

where my selectArrayAssoc function as following

public function selectArrayAssoc($sql, $params = array())
{
  try {
     $sth = $this->db->prepare($sql);
     $sth->execute($params);
     $result = $sth->setFetchMode(PDO::FETCH_ASSOC);
     return $sth->fetchAll();
  } catch(PDOException $e) {
     print $e->getMessage();
     //Log this to a file later when in production
     exit;
  }
}

it does not take the quoted variables, I think it is suppressing, in such cases how to deal with this.


回答1:


When using prepared statement placeholders (parameter binding) in general, each occurrence of a placeholder holds exactly one variable.

You're trying to pass several. What's happening is basically that your parameters are escaped: Your :states is replaced with '''SC'',''SD''' or '\'SC\',\'SD\'' internally, rather than with just the raw 'SC','SD' that you want.




回答2:


pinkgothic is absolute correct. But I think you got the problem, that you have an array of 'states' and want work with this array. You've to prepare the Placeholder for each value in the query.

$states = array('SC','SD');
$phArray = array();
$valArray = array();

foreach($ids AS $key=>$value){
  array_push($phArray, ':PH' . $key);
  $valArray[':PH' . $key] = $value;
}

$sql = 'select * from mytable where states in (' . implode(',', $phArray) . ')';
$params = array($valArray);
$result = $this->selectArrayAssoc($sql, $params);


来源:https://stackoverflow.com/questions/2681281/pdo-and-sql-in-statements

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