0

When working on a site, I found a fairly weird issue with PDO. The following code only selects posts made by user 1, not or 3.

$sql = "SELECT postid FROM posts WHERE userid IN (:friends)";
$pdo->prepare($sql);
$pdo->execute(array(':friends' => '1, 2, 3'));

However the following code selects post from all three:

$sql = "SELECT postid FROM posts WHERE userid IN (1, 2, 3)";
$pdo->prepare($sql);
$pdo->execute();

Why is this, and what can I do to make the first work like the second?

  • Something is missing - `selects posts made by user 1, not or 3`. Do you mean `1, not 2 or 3`? – Techie May 14 '16 at 15:10
  • Possible duplicate of [PHP PDO prepared statement IN() array](http://stackoverflow.com/questions/21763224/php-pdo-prepared-statement-in-array) – Dave Ross May 14 '16 at 15:12
  • 1
    Possible duplicate of [PDO binding values for MySQL IN statement](http://stackoverflow.com/questions/1586587/pdo-binding-values-for-mysql-in-statement) – david strachan May 14 '16 at 19:27

1 Answers1

0

You must write query like this

$sql = "SELECT postid FROM posts WHERE userid IN (:friend1, :friend2, :friend3)";
$pdo->prepare($sql);
$pdo->execute([
    ':friend1' => '1',
    ':friend2' => '2',
    ':friend3' => '3',
]);
Nick
  • 9,735
  • 7
  • 59
  • 89