[英]PHP PDO for NOT IN query in MYSQL
I have a post variable called $_POST['excludeids']
with the following value: 我有一个名为
$_POST['excludeids']
的发布变量,其值如下:
1,2,3,4,5,6,7,8,9
I want to pass this into an SQL query through NOT IN
so I use the following query: 我想通过
NOT IN
将其传递到SQL查询中,因此我使用以下查询:
$STH = $DBH->prepare("SELECT * FROM books WHERE id NOT IN (:excludeids)");
$STH->bindValue(':excludeids', $_POST['excludeids']);
$STH->execute();
Binding the variable doesn't work in this context I don't know why. 在这种情况下,绑定变量不起作用,我不知道为什么。 What's wrong with the above query?
上面的查询有什么问题?
It doesn't work in this way because an IN()
clause expects a collection of values, not a comma separated string, which is what you are providing by attempting to bind them all as a single argument. 它不能以这种方式工作,因为
IN()
子句期望值的集合,而不是逗号分隔的字符串,这是通过尝试将它们全部绑定为单个参数而提供的。
In order to make this work you will need to bind each element in the collection individually: 为了完成这项工作,您将需要分别绑定集合中的每个元素:
// 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();
您将必须遍历id(首先将它们分解为数组)并在SQL字符串中和使用bindValue
动态创建新参数。
$all_id = array(1, 2, 3, 4,5);
$countArr = count($all_id);
for($countArr; $countArr > 0; $countArr--)
$in[]= '?';
$in = implode(', ', $in);
$stmt = $dbh->prepare("
SELECT ID
FROM b_iblock_element
WHERE XML_ID NOT IN ( ".$in.")
");
if ($stmt->execute($all_id)) {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<pre>'; print_r($row); echo'</pre>';
}
}
$stmt->execute();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.