sql准备的语句不适用于WHERE <column> IN子句

时间:2020-02-21 21:26:53

标签: php mysql sql prepared-statement

所以我有这个sql前置语句:

SELECT carName, modelName 
FROM cars 
INNER JOIN model ON cars.idCar = model.idCar 
WHERE carName IN (?)`

$input = " 'toyota','honda' "

我试图将其放入sql语句中,但是它给出了零行。我已经尝试在phpMyAdmin中查询,并且一切正常。有人知道这个问题吗?

2 个答案:

答案 0 :(得分:1)

IN列表中,每个值需要一个参数。如果您传递单个参数,则它将被解释为包含逗号的唯一字符串,这不是您想要的(并且最终不会匹配,因为表中的名称均不匹配该值)。

因此,对于两个参数:

SELECT carName, modelName 
FROM cars 
INNER JOIN model ON cars.idCar = model.idCar WHERE carName IN (?, ?);

答案 1 :(得分:1)

IN子句采用多个参数,并且每个参数只能采用一个值。因此,要自动执行在此语句中插入多个参数的过程,可以使用如下所示的内容:

/* Execute a prepared statement using an array of values for an IN clause */
$params = ['toyota', 'honda'];
/* Create a string for the parameter placeholders filled to the number of params */
$place_holders = implode(',', array_fill(0, count($params), '?'));

/*
    This prepares the statement with enough unnamed placeholders for every value
    in our $params array. The values of the $params array are then bound to the
    placeholders in the prepared statement when the statement is executed.
    This is not the same thing as using PDOStatement::bindParam() since this
    requires a reference to the variable. PDOStatement::execute() only binds
    by value instead.
*/
$st = $db->prepare("SELECT carName, modelName FROM cars WHERE carName IN ($place_holders)");
$st->execute($params);
相关问题