2012-07-30 96 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);