2011-10-07 41 views
0

我在做什麼錯了?MySql選擇哪裏或哪裏不是...而許多其他「Ands」和「Ors」

我想選擇只有天主教的教堂,但它是選擇更多。是因爲拉鍊嗎?他們工作得很好。

$Zips = array(60618,60625,60647,60641,60613,60657,60640,60659,60614,60639,60622,60630,60660,60651,60642,60645,60712,60612,60646,60624,60610,60626,60674,60654,60661,60644,60634,60606,60607,60707,60302,60611,60202,60602,60601,60706,60303,60603,60604,60301,60701,60656,60076,60204,60209,60304,60077,60623,60608,60305,60203,60605,60631,60664,60668,60669,60670,60673,60675,60677,60678,60680,60681,60684,60685,60686,60687,60688,60690,60691,60693,60694,60696,60697,60699,60689,60695,60171,60201,60682,60208,60053,60804,60714,60616,60130,60161,60153,60176,60068,60160,60029,60141,60091,60402,60632,60131,60290,60165,60609,60043,60164,60546); 
$ZipCount = count($Zips); 

for ($i = 0; $ZipCount > $i; $i++) { 
    if ($i == 0) { 
     $TheZips = "Zip LIKE '%$Zips[$i]%'"; 
    } 
    else { 
     $TheZips .= "OR Zip LIKE '%$Zips[$i]%'"; 
    } 
} 

$sql = mysql_query("SELECT DISTINCT * FROM info WHERE Catholic and '%true%' OR $TheZips"); 
$result = mysql_num_rows($sql); 
+0

'拉鍊IN(1,2,3,4)' – teemitzitrone

回答

4
$str_zips = implode(', ', $Zips); 

$sql = 
mysql_query("SELECT DISTINCT * FROM info WHERE Catholic=true AND Zip IN ({$str_zips})"); 
3

恕我直言,你應該使用:

for($i=0;$ZipCount>$i;$i++) 
{ 
    if($i==0){ $TheZips= "Zip = '$Zips[$i]'"; } 
    else { $TheZips.= "OR Zip = '$Zips[$i]'";} 
}  

$sql = mysql_query(
    "SELECT DISTINCT * FROM info WHERE Catholic=true AND ($TheZips)"); 

for($i=0;$ZipCount>$i;$i++) 
{ 
    if($i==0){ $TheZips= "$Zips[$i]"; } 
    else { $TheZips.= ",$Zips[$i]";} 
}  

$sql = mysql_query(
    "SELECT DISTINCT * FROM info WHERE Catholic=true AND Zip IN ($TheZips)"); 
+0

使用破滅(),而不是for循環。 –

+0

@Robin Castlin:是的,你說得對,但我不想複製你的好答案(爲你+1):) – Marco