Jump to content

Archived

This topic is now archived and is closed to further replies.

extrovertive

Using an array in MySQL where id IN ($array)?

Recommended Posts

I have an array - $zips = array('92120', '92127')

$zips actually contain a hundred more is generated dynamically.

Now, can I use this kind of SQL?

SELECT username, zip FROM usertable
WHERE zip IN ('$zips')

I tried but it doesn't work. Basically, $zips is an array that contain a lot of zip codes from a class I'm using. However, I can't use an array in a "IN" statement for MySQL?

Share this post


Link to post
Share on other sites
no you can, you have to separate all zipcodes into a string:
SELECT username, zip FROM usertable WHERE zip IN ('92120', '92127');

it's easy to write a snippet of code to convert your array into a string like that.

Share this post


Link to post
Share on other sites
I'm trying implode:


$zips = array('92120', '92127');
$zips = implode(',',$zips);
SELECT username, zip FROM usertable WHERE zip IN ($zips);

yields no result, yet just using WHERE zip IN ('92120', '92127') does. I have also implode it using '', ',' but still doesnt' work. FIND_IN_SET give the same result.

Share this post


Link to post
Share on other sites
Ah, here's the solution.
$zips = array(92102, 92127, 92103);
$quoted_zips= array();
foreach ($zips AS $v)
{
    $quoted_zips[]= "'{$v}'";
}
$zip_list= implode(',', $quoted_zips);

SELECT username, zip FROM usertable
WHERE zip IN ($zips)

Share this post


Link to post
Share on other sites
Guest
This topic is now closed to further replies.

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.