PHP 字符串在 MYSQL IN() 中不起作用

PHP string does not work in MYSQL IN()

我只是添加代码,因为它会说明一切。是的,它不起作用,我不知道为什么 :(

$array = array('One', 'Two', 'Three');
$string = "'" . implode("', '", $array) . "'";

$query = "SELECT * FROM $table WHERE name IN (" . $string . ")";
$make = $this->conn->prepare($query);
$make->execute();
$result = $make->fetchAll();

它returns 空数组。谢谢你的帮助。

出现问题是因为您在尝试传递给 table 的值中有单引号,即 "Man-o'-War".

因为您使用的是数组和准备好的语句,所以您应该在执行查询时传递数组:

$array = array('One', 'Two', 'Three');

$query = "SELECT * FROM $table WHERE name IN (" . implode(',',str_split(str_repeat('?',count($array)))).") ";
$make = $this->conn->prepare($query);
$make->execute($array);
$result = $make->fetchAll();

为了确保我们有足够的位置占位符,我们对 implode(), str_split() and str_repeat() 施展了一点魔法,以便在语句中获得足够的 ?

来自Demystifying PHP's Data Objects (PDO)

YOU MUST pass all values to bind in an array to PDOStatement->execute() or you have to bind every value with PDOStatement->bindValue(), then call PDOStatement->execute() with no parameters. Passing an array (empty or not) to execute() will replace any previous bindings and can lead to errors, e.g. with MySQL the error "SQLSTATE[HY000]: General error: 2031" (CR_PARAMS_NOT_BOUND) if you passed an empty array.

另一个注意事项,确保 $table 被正确填充(并且 没有 ,你不能在 PDO 中传递 table 或列名作为参数) .