2012-07-30 97 views
0

你好,我試圖計算有多少行位於列中,其中名稱包括任何名稱在預定義的$ uk_array。MySQL like子句不能對數組php

mysql打印出我沒有任何值的列「有()」與數組中的名稱相匹配,但有一個「Dublin,Ireland」。

下面是代碼:

<?php 
    include'connect.php'; 
    $uk_array = array('Liverpool','London','London UK','UK','London', 
    'Dublin, Ireland','Manchester','Norwich','United Kingdom','Norwich','Duplin','England','ENGLAND', 
    'united kingdom'); 

    $string = ''; 

    foreach($uk_array as $term=>$i) { 
     $string = $string."location LIKE '%".$i."%' AND"; 
    } 
    $string = substr($string, 0, -5); 
    $query="SELECT COUNT(location) as location FROM tweets WHERE $string"; 
    $result = mysql_query($query) or die(mysql_error()); 
    while($row = mysql_fetch_array($result)){ 
     echo "There are ". $row['location'].""; 

    } 


    ?> 
+0

編寫代碼之前,更注重你的邏輯。 – Matt 2012-07-30 13:17:55

+0

如果你沒有部分地點匹配,可以使用WHERE IN IN('Dublin','Liverpool','London',...)'而不是LIKE,它的速度更快,更乾淨。 – ddinchev 2012-07-30 13:18:50

+0

缺少空間。這就是我要說的...... – DaveRandom 2012-07-30 13:20:03

回答

4

你應該做

$string = $string."location LIKE '%".$i."%' OR"; 

開關與運算與OR操作,否則現場必須包含在uk_array所有的值。

另外,你有一個錯字 - Duplin?

編輯:更多的錯誤

foreach($uk_array as $term=>$i) { 
    if($term) $string .= ' OR '; // only append OR if it's not the first one 
    $string .= "location LIKE '%".$i."%'"; 
} 
+0

與或我得到這個錯誤:你的SQL語法錯誤;檢查與您的MySQL服務器版本對應的手冊,在第1行'%united kingdom%'附近使用正確的語法 – 2012-07-30 13:20:03

+0

再次複製 - 這是因爲您在查詢中有類似OR%united kingdom%的內容。你也需要空間。 – Summoner 2012-07-30 13:20:41

0

您可能需要使用OR操作

// change this 
    // $string = $string."location LIKE '%".$i."%' AND"; 
    // to 
    $string = $string."location LIKE '%".$i."%' OR"; 
// and 
// $string = substr($string, 0, -5); 
// to 
$string = substr($string, 0, -3);