PHP MySQL检查表中是否存在数组中的项,然后显示

时间:2014-10-03 22:09:18

标签: php mysql database

PHP 5.4 with MySQL

建立起来:

<?php
   $arr = ...
   $sql = 'SELECT COUNT(*) FROM table WHERE field IN ( ' . implode( ',', $arr ) . ' );';
   $result = $db->query( $sql );
?>

如何显示表格中哪些项目不在表格中?

5 个答案:

答案 0 :(得分:4)

不是返回计数,而是返回字段本身:

$sql = 'SELECT field WHERE field IN ' . implode( ',', $arr ) . ' );';
$result = $db->query($sql);
$found = array();
while ($row = $result->fetch_assoc()) {
    $found[] = $row['field'];
}

然后你可以比较两个数组:

$not_found = array_diff($arr, $found);

答案 1 :(得分:1)

如果您的$arr变量已经过清理且可以安全地构建查询,您可以使用union运算符构建一个包含数组中所有单词的表,然后您可以将该表连接到table.field并且只保留没有匹配项的数组项。

$arr = array('one','two');
$sql = "select item from (
      select '" . implode("' item union select '",$arr). "' item
    ) t1 left join table t2 on t2.field = t1.item
    where t2.field is null";

这将生成以下sql

select item from (select 'one' item union select 'two' item) t1 
    left join table t2 on t2.field = t1.item
    where t2.field is null

答案 2 :(得分:0)

只是提出一个想法(这可能不会起作用)

$arr = ...
$sql = 'SELECT field FROM table WHERE field IN ( ' . implode( ',', $arr ) . ' );';
$result = $db->query( $sql );
while($r = $result->fetch())
    $arr2[] = $r['field'];
print_r(array_diff($arr,$arr2));

答案 3 :(得分:0)

在你完成imloud之后,数组不再是一个数组,这是一个字符串,所以你不必选择count(*)。您需要在执行while之后选择id并比较数组

答案 4 :(得分:0)

如果您的商品最多包含10个元素,请使用&#34; NOT IN&#34;

<?php
   $arr = array('one','two');
   $filterExisting = "'" . implode("', '", $arr ) . "'";
   $sql = "SELECT COUNT(*) FROM table WHERE field NOT IN (". $filterExisting .")";
   $result = $db->query($sql);
?>