PHP PDO for MYSQL中的NOT IN查询

Mic*_*uel 4 php mysql sql pdo

我有一个$_POST['excludeids']使用以下值调用的post变量:

1,2,3,4,5,6,7,8,9
Run Code Online (Sandbox Code Playgroud)

我想将此传递给SQL查询,NOT IN因此我使用以下查询:

$STH = $DBH->prepare("SELECT * FROM books WHERE id NOT IN (:excludeids)");
$STH->bindValue(':excludeids', $_POST['excludeids']);
$STH->execute();
Run Code Online (Sandbox Code Playgroud)

绑定变量在这种情况下不起作用我不知道为什么.上面的查询有什么问题?

Dav*_*dom 8

它不能以这种方式工作,因为IN()子句需要一组值,而不是逗号分隔的字符串,这是您通过尝试将它们作为单个参数绑定而提供的.

为了完成这项工作,您需要单独绑定集合中的每个元素:

// Split the IDs into an array
$ids = preg_split('/\s*,\s*/', $_POST['excludeids'], -1, PREG_SPLIT_NO_EMPTY);

// Create an array of ? characters the same length as the number of IDs and join
// it together with commas, so it can be used in the query string
$placeHolders = implode(', ', array_fill(0, count($ids), '?'));

// Prepare the statement
$STH = $DBH->prepare("SELECT * FROM books WHERE id NOT IN ($placeHolders)");

// Iterate the IDs and bind them
// Remember ? placeholders are 1-indexed!
foreach ($ids as $index => $value) {
    $STH->bindValue($index + 1, $value, PDO::PARAM_INT);
}

// This should now work
$STH->execute();
Run Code Online (Sandbox Code Playgroud)