0

PHP 5.4 with MySQL

Building off of this:

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

How would I display which items of the array ARE NOT in the table?

0

5 Answers 5

5

Instead of returning the count, return the field itself:

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

Then you can compare the two arrays:

$not_found = array_diff($arr, $found);
Sign up to request clarification or add additional context in comments.

8 Comments

You could also unset the found items from $arr, and then just display whatever is left.
You set that earlier in your script, didn't you? It's in $arr = ...
Yeah my bad. So now it shows me every array value, instead of the values that do not exist in the table
I guess what I'm looking for is: For each item in the array, check to see if it exists in the table. If it doesn't push it to a new array. If it does exists, do not add it to the new array
You can do whatever you want with $not_found, it's just an array containing all the values that weren't found.
|
1

If your $arr variable is sanitized and safe to build a query with, you can use union operators to build a table containing all the words in the array, then you can left join that table to table.field and only keep array items where there was no match.

$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";

this will produce the following 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

1 Comment

How would I display the data?
0

Just to give an idea (this probably won't work)

$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));

Comments

0

after you've done imloud, array ceases to be an array, this is a string, so you do not have to select count(*). You need to select id after do the while and compare arrays

Comments

0

Just use "NOT IN", if your items is up to 10 elements:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.