duancuisan2503 2016-12-31 17:03
浏览 17
已采纳

允许用户在一个字段中搜索两个搜索词

Is there a way I can have a single input field, called "Location" and allow the user to type in either a postcode OR town name to retrieve a business listing? eg. Bristol or BS6 6NX

Below is my table structure currently

Business: (with example data)
id - 1
name - Apples
location - bristol
postcode - bs5 6nx

Locations: (with example data)
id - 1
name - bristol
postcode - bs5 6

My current query is:

$query = "
            SELECT b.id, b.name, b.category, b.thumb_picture, b.location
            FROM business b 
            LEFT JOIN locations l ON b.location = l.name 
            WHERE l.name = ".$dbh->quote($userLocation)."
            OR l.postcode LIKE ".$dbh->quote($userLocation."%")."
            GROUP BY b.name
            ORDER BY b.date DESC";

Which will only work with town names currently.

Update:

How to detect an address or a postal code in a variable

Seems to be a solution, identify if the field is a postcode or town before hand, and then perhaps have 2 queries depending on the result? One to search the postcode column and one to search town?

  • 写回答

2条回答 默认 最新

  • 「已注销」 2016-12-31 17:57
    关注

    One solution I've found with a little more digging is below. I first determine if a postcode or a town has been entered. Then do the appropriate query.

    function IsPostcode($postcode)
    {
        $postcode = strtoupper(str_replace(' ','',$postcode));
        if(preg_match("/(^[A-Z]{1,2}[0-9R][0-9A-Z]?[\s]?[0-9][ABD-HJLNP-UW-Z]{2}$)/i",$postcode) || preg_match("/(^[A-Z]{1,2}[0-9R][0-9A-Z]$)/i",$postcode))
        {    
            return true;
        }
        else
        {
            return false;
        }
    }
    
    $ul = "ze3 9";
    if (IsPostcode($ul)) {
        $where = "
        LEFT JOIN locations l ON l.name = b.location
        WHERE l.postcode LIKE ".$dbh->quote($ul.'%')."";
    
    }
    else {
        $where = "
        LEFT JOIN locations l ON l.name = b.location
        WHERE l.name LIKE ".$dbh->quote($ul.'%')."";
    }
    
    $query =    "SELECT b.id, b.name, l.name, l.postcode
                FROM business b
                ".$where."
                ORDER BY b.date DESC";
    

    Can anyone see a fault with this?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景