使用PHP和MySQL,如何将变量发送到WHERE ... IN子句?

时间:2016-04-14 15:33:35

标签: php mysql

以下SELECT语句可以正常工作:

try {     
  $sql = $db->prepare('SELECT *
                       FROM classes
                       WHERE classes.id IN (65,70,80)');
  $sql->execute();
  $sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
  echo $e->getMessage();
  die();
}

但是当我尝试将变量发送到WHERE子句时,我只返回一行。

在这种情况下,$ ids是一个看起来像'65,70,80'的字符串。

try {     
  $sql = $db->prepare('SELECT *
                       FROM classes
                       WHERE classes.id IN (?)');
  $sql->bindParam(1, $ids);
  $sql->execute();
  $sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
  echo $e->getMessage();
  die();
}

我是否需要更改获取数据的方式,或者我的语法错误?

A-HA!感谢Mihai的链接。这是有效的代码:

首先:不要传入字符串,而是将id放入$ ids数组中。

// Figure out how many ? marks have to be in your query as parameter placeholders.
$count = count($ids);
$arrayOfQuestions = array_fill(0, $count, '?');
$queryPlaceholders = implode(',', $arrayOfQuestions);

try {     
  $sql = $db->prepare('SELECT *
                       FROM classes
                       WHERE classes.id IN (' . $queryPlaceholders . ')');
  $sql->execute($ids);
  $sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
  echo $e->getMessage();
  die();
}

1 个答案:

答案 0 :(得分:0)

试试这个:

try {     
  $sql = $db->prepare('SELECT *
                       FROM classes
                       WHERE classes.id IN (?)');
  $sql->bindParam(1, explode(',', $ids));
  $sql->execute();
  $sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
  echo $e->getMessage();
  die();
}