-1

The following SELECT statement works just fine:

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();
}

BUT when I try to send a variable into the WHERE clause, I only get one row back.

In this case $ids is a string that looks like '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();
}

Do I need to change the way I'm fetching the data, or is my syntax wrong?


A-HA! Thanks for that link Mihai. Here's the code that works:

First: instead of passing in a string, put ids into an $ids array.

// 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();
}
B. Krafft
  • 147
  • 1
  • 13
  • 1
    You are binding a string so it will look for `'65,70,80'` Look here http://stackoverflow.com/questions/920353/can-i-bind-an-array-to-an-in-condition – Mihai Apr 14 '16 at 15:34
  • if `$ids` is an `array` change your code to `$sql->bindParam(1, implode(',', $ids));` – RST Apr 14 '16 at 15:38
  • What is the type of `$ids`? Array? String? – mferly Apr 14 '16 at 15:40
  • Please don't edit your question to add an answer. If you have an answer to the question you asked, add it as an *answer* to the question. – spencer7593 Apr 15 '16 at 13:31

1 Answers1

0

Try this:

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();
}
maxpovver
  • 1,580
  • 14
  • 25
  • When I test this I get an "Array to String Conversion" error. The question that Mihai refers to above got me on the right track. – B. Krafft Apr 15 '16 at 13:15