Forum Moderators: open

Message Too Old, No Replies

SQL select pulling from PHP array?

sql php array

         

AndieR

10:00 pm on Dec 26, 2007 (gmt 0)

10+ Year Member



Hello to all,

I am trying to use data from one of my PHP arrays to perform a select in SQL... I hav never tried my hand at this and have been browsing the topic but haven't been able to find any reliable info... Any tips or ideas would be greatly appreciated!

$narray["$zip1"]="$red"; (this is inside a loop and so resturns several rows)

asort($narray);

foreach($narray as $key => $value)
{
print $key . " = " . $value . "<br />";
}

$query="SELECT * FROM schools WHERE zip = '$key'";
$result=mysql_query($query) or die ("Query failed");

Of course there are several keys and I suppose I'd need some loop but I can't seem to link both in my head and picture the global idea... :(

Thanks!
Andie

coopster

2:46 am on Dec 27, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Sounds like you are looking for ... perhaps either an IN [dev.mysql.com] comparison or better yet a UNION [dev.mysql.com] query?

ZydoSEO

8:54 pm on Dec 27, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



As Coopster said, sounds like you need to be using an IN clause as part of your where clause...

For instance if your key in your table are integer values, you my try to builds a string that looks like:

SELECT * FROM schools WHERE zip IN (28226, 28225, 28211)

if your PhP array has the values 28226, 28225, and 28211 in it.

If your key in your table is a string value, you may try to build a string that looks like:

SELECT * FROM schools WHERE zip IN('28226', '28225', '28211')

Simply cycle through the table concatenating your zips into a string like "(28226, 28225, 28211)" and then concatenate the resulting string of zips onto the end of another string that contains "SELECT * FROM schools WHERE zip IN ".

Note: It's okay if the array only has one value in it.

SELECT * FROM schools WHERE zip IN (28226) is logically equivalent to SELECT * FROM schools WHERE zip = (28226).

[edited by: ZydoSEO at 8:55 pm (utc) on Dec. 27, 2007]

AndieR

9:03 pm on Dec 27, 2007 (gmt 0)

10+ Year Member



Hello!

Thanks :) I had ended up creating a variable with the following: "OR zip = '3333' OR zip = '2344'" etc and using it in my query but the IN method is much better!

Thanks
Andie