简体   繁体   中英

Trying to figure out PHP PDO prepared statements and placeholders. Placeholder in “IN” clause of MySQL statement

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM