Web Hosting Talk







View Full Version : [MySQL] Selecting row from array and compare on first two characters


ic3d
05-18-2007, 08:56 PM
Hi Everyone,

My English is not very well but i'll try to explain what iam looking for.

I have an array in PHP with about 10 different numeric values between 10 and 99. E.g. $array[0] = 17; $array[1] = 41; and so on. I want to compare this array with the first two characters of a row in a database. For example 41210 should match because 41 is in the array in PHP. But 17210 should match as well.

Is there any way to do this? Iam at the very basic sql-statement now but can't find what to do next.

mysql_query("SELECT * FROM table WHERE the_first_two_chars_of_zipcode = '$everything_in_this_array'");

luki
05-19-2007, 12:25 AM
Simple:

$zips = implode(',', $your_array);
mysql_query("SELECT * FROM table WHERE LEFT(zipcode,2) IN($zips)");

ic3d
05-19-2007, 06:29 AM
Thanks Luki, that's great!

I forgot to mention in my startpost that i want to prevent a loop because i don't like to use multiple loops inside eachother, so i was looking for something like inarray and your code looks like it's doing that :)

I'll try your code and look up what WHERE LEFT and IN exactly is.