2

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) . ')
          ");
8
  • You need quotes around the names: in ('john','peter','jack') Commented Oct 25, 2013 at 10:45
  • 1
    $db->query("SELECT contactname FROM contacts WHERE contactname NOT IN ('" . implode(",", $name_array) . "') "); implode should be out of the quotes Commented Oct 25, 2013 at 10:46
  • @ManZzup: That won't work. Commented Oct 25, 2013 at 10:47
  • I put the quotation marks around the array variable but I still get the array to string warning Commented Oct 25, 2013 at 10:49
  • @user2014429: You need to add the quotes around every single name and not around all of them. Commented Oct 25, 2013 at 10:49

4 Answers 4

5

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)
          ");
Sign up to request clarification or add additional context in comments.

2 Comments

I tried this and I really thought it would work because it seems to solve the problem of the quotation marks for the indexes. But for some reason I'm still getting the blasted array to string warning. But still +1 because it should have solved the problem.
UPDATE - there was something unrelated which was preventing it from working, now the code works great. Thank you very much.
3

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

Comments

2

Try to use FIND_IN_SET()

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

Comments

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

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.