PHP MySQL WHERE LIKE

时间:2012-08-03 10:57:12

标签: php mysql

我试图使用mysql select只返回某个列的结果,'category'包含一个id,例如在字段中可能有'1,2,4'。我想使用一个变量来查看该字段中是否存在该ID。

到目前为止

代码:

   function returnSQLByCategory($criteria) {
    $lat = $criteria['lat'];
    $lng = $criteria['lng'];
    $categoryid = $criteria['categoryid'];
    $page_number = $criteria['page_number'];
    $nb_display = $criteria['nb_display'];

    //if($page_number=='') $page_number=1;
    //if($nb_display=='') $nb_display=10;
    $start = ($page_number*$nb_display)-$nb_display;

    $sql = "SELECT company, name, lng, lat, address, city, country, zip, link,
    ( 3959 * acos( cos( radians('".mysql_real_escape_string($lat)."') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('".mysql_real_escape_string($lng)."') ) + sin( radians('".mysql_real_escape_string($lat)."') ) * sin( radians( lat ) ) ) ) AS distance 
    FROM locations WHERE categoryid LIKE '%$categoryid%'";

    $sql .= " ORDER BY distance";

    return $sql;
    }

这不起作用,并且必须返回'1',因为我只能看到categoryid'1'中的行。如果我手动输入语句'2'或示例,它按预期工作!

非常感谢,谢谢。

3 个答案:

答案 0 :(得分:0)

为什么不使用IN?

categoryid IN ('.$categoryid.')

答案 1 :(得分:0)

SELECT 
    company, 
    name, 
    lng, 
    lat, 
    address, 
    city, 
    country, 
    zip, 
    link 
FROM 
    locations 
WHERE 
    MATCH (categoryid) AGAINST ($categoryid IN BOOLEAN MODE)

使用MATCH怎么样,但是用逗号分隔你的类别id字符串需要用一个空格分隔。即。('1 2 3 4')并在您的sql语句中用单引号括起来。

答案 2 :(得分:-1)

$categoryid = 1;
$categoryid = mysql_real_escape_string($categoryid);

$sql = "SELECT * FROM `locations` WHERE categoryid = '$categoryid'";

$result = mysql_query($sql);