提问者:小点点

包含数组的in子句的PDO查询将不起作用[重复]


我有这个代码:

$Array=array();
array_push($Array,"Email1","Email2");
$Array=implode("','",$Array);
$Array="'$Array'";
echo "$Array" //Will output 'Email1','Email2'
$Check=$connection->prepare("SELECT ID FROM USERS WHERE EMAIL IN(:Array)");
$Check->execute(array(
    ':Array' => $Array,
));

此查询不起作用,但如果我写:

$Check=$connection->prepare("SELECT ID FROM USERS WHERE EMAIL IN('Email1','Email2')");
$Check->execute(array(
    ':Array' => $Array,
));

这是可行的,但我不会绑定数组以避免SQL注入。我怎样才能修好它?


共1个答案

匿名用户

您不希望将内爆列表绑定为一个元素,而是使用将每个值单独绑定所以语句的结尾应该是其中电子邮件(?,)

$values  = ["Email1","Email2"];
# This should give you ?,?
$bindstr = implode(",",array_fill(0,count($values),'?'));
$query = $connection->prepare("SELECT ID FROM USERS WHERE EMAIL IN({$bindstr})");
# Use the raw values individually in the execute
$query->execute($values);

希望这会得到你想要的结果。