Select on array values?

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
arielle
Forum Newbie
Posts: 3
Joined: Mon Jan 17, 2005 10:39 am
Location: Albuquerque, NM

Select on array values?

Post by arielle »

I have a PHP script that takes user entered zip code and radius values, and retrieves the matching zip codes in that radius to an Array.

My question is: How can I then take this Array, and SELECT entries (from a table with a "zip" column) where zip = "any value in the zip Array".

Sorting will be provided on the results pages, so is not critical to have them sorted in any particular way initially. Any help is greatly appreciated!

Thanks,
-Arielle
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

$array = array(90210,75282,94558);
if(!empty($array))
  $zips = '''' . join(''',''', $array) . '''';
else
  $zips = 'NULL';

$sql = 'SELECT * FROM `table` WHERE `zip` IN( ' . $zips . ' );';

what's with all these people asking about zip codes today? :P
arielle
Forum Newbie
Posts: 3
Joined: Mon Jan 17, 2005 10:39 am
Location: Albuquerque, NM

Post by arielle »

feyd wrote:

Code: Select all

$array = array(90210,75282,94558);
if(!empty($array))
  $zips = '''' . join(''',''', $array) . '''';
else
  $zips = 'NULL';

$sql = 'SELECT * FROM `table` WHERE `zip` IN( ' . $zips . ' );';
Thanks, feyd, I'll give that a go. Do you mind elaborating on what's happening on line 3, so I understand when I run across something like this later?
feyd wrote:what's with all these people asking about zip codes today? :P
I guess we're all going postal. 8O

-Arielle
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

http://php.net/join

line 3 is fairly simple.. I asked it to stick all the values of the array $array into a single string, with ',' seperating each one. At the same time, I told php to place a single quote on each side of the returned string. So it'll looks like this:

Code: Select all

'90210','75282','94558'
arielle
Forum Newbie
Posts: 3
Joined: Mon Jan 17, 2005 10:39 am
Location: Albuquerque, NM

Post by arielle »

feyd wrote:http://php.net/join

line 3 is fairly simple.. I asked it to stick all the values of the array $array into a single string, with ',' seperating each one. At the same time, I told php to place a single quote on each side of the returned string. So it'll looks like this:

Code: Select all

'90210','75282','94558'
Thanks again, feyd. This is very helpful!

Cheers,
Arielle
Post Reply