user2014429
user2014429

Reputation: 2577

select from table not in php array query not working

I get an array to string conversion warning when I try to select using my $name_array variable in the NOT IN clause. I have tried loads of different quotation combinations, but I either get a syntax error or an array to string conversion warning. can anyone see what I'm doing wrong here. Thanks.

$db->query("SELECT contactname
            FROM contacts 
            WHERE contactname 
            NOT IN (' . implode(",", $name_array) . ')
          ");

Upvotes: 2

Views: 2125

Answers (4)

smart developer
smart developer

Reputation: 224

You have to quote name in '' due to string so please use.

$val="'";
$val.=implode("','",$name_array);
$val.="'";
$db->query("SELECT contactname FROM contacts WHERE contactname NOT IN ($val) ");

This will defiantly help you

Upvotes: 3

Adnan
Adnan

Reputation: 579

$db->query("SELECT contactname
            FROM contacts 
            WHERE contactname 
            NOT IN ('".implode("','",$name_array).'\')');

Upvotes: 1

valex
valex

Reputation: 24144

Try to use FIND_IN_SET()

$db->query("SELECT contactname
            FROM contacts 
            WHERE NOT FIND_IN_SET(contactname, \'' . implode(",", $name_array) . '\')   
          ");

Upvotes: 2

Barmar
Barmar

Reputation: 781878

You need to put quotes around each name before imploding them into a list.

$names = implode(",", array_map(function($x) { return "'$x'"; }, $name_array));
$db->query("SELECT contactname
            FROM contacts 
            WHERE contactname 
            NOT IN ($names)
          ");

Upvotes: 5

Related Questions