0

I'm new to PDO and prepared statements. Why does this work:

$sth = $dbh->prepare("SELECT * 
                      FROM skyrim_ingredients 
                      WHERE ing_name 
                      IN ('blue butterfly wing', 'blue dartwing', 'blue mountain flower');");
while($row = $sth->fetch()) {
    echo $row['ing_id'];
}

...but this doesn't:

$ing_string = 'blue butterfly wing', 'blue dartwing', 'blue mountain flower';
$sth = $dbh->prepare("SELECT * 
                      FROM skyrim_ingredients 
                      WHERE ing_name 
                      IN (?);");
$sth->bindParam(1, $ing_string);
$sth->execute();
while($row = $sth->fetch()) {
    echo $row['ing_id'];
}

I read that you cant use parameters for tables or columns, is this the case with IN clause, too?

pdizz
  • 4,100
  • 4
  • 28
  • 42
  • 2
    You should refer to this answer, it explains your exact problem, http://stackoverflow.com/questions/920353/php-pdo-can-i-bind-an-array-to-an-in-condition tho you would need to change `$ing_string` to an array – Lawrence Cherone Apr 19 '12 at 04:30
  • This is the solution I ended up using. Thanks – pdizz Apr 19 '12 at 16:48

1 Answers1

1

Parameter substitution using ? is not the same as variable expansion -- which is what it looks like you're expecting in the case that doesn't work. The actual SQL that gets to the db might look like ... IN ("'blue butterfly wing', 'blue dartwing', 'blue mountain flower'"), so of course it wouldn't work.

belwood
  • 3,320
  • 11
  • 38
  • 45
  • I was thinking string substitution. I didn't realize I would need a separate placeholder for each value, not just the whole string. – pdizz Apr 19 '12 at 14:32