【问题标题】:Search multiple columns in MySQL using PHP使用 PHP 在 MySQL 中搜索多个列
【发布时间】:2012-05-15 09:35:49
【问题描述】:

我在互联网上搜索了很多不同的方法,但找不到我的问题的答案。我正在自学网站开发,并正在尝试创建一个在线房地产网站。

当我尝试搜索房产时,我的问题出现了。例如,我想搜索特定区域或邮政编码中的所有属性。当我尝试搜索地址行 1、地址行 2、邮政编码和区域(如 London SW1V)等多个字段时。

以下是我目前正在使用的查询,并希望将其更改为我需要的工作方式:

SELECT property.propertyid, property.propertyname
FROM   property
WHERE  property.address_1 LIKE '%txtSearchField%'
    OR property.address_2 LIKE '%txtSearchField%'
    OR property.postcode  LIKE '%txtSearchField%'
    OR property.area      LIKE '%txtSearchField%'

【问题讨论】:

  • 到底是什么问题?您的查询看起来不错。我可以确认您确实正确地插入了变量并且没有在表中搜索“txtSearchField”吗?
  • 如果你不使用连接查询,不需要把表名放在属性之前,你可以使用propertyId,propertyname,...

标签: php mysql search


【解决方案1】:

这种方法效率不高,但最简单且适用于低流量页面:

SELECT property.propertyid, property.propertyname
FROM   property
WHERE  CONCAT(property.address_1, ' ',
              property.address_2, ' ',
              property.postcode, ' ',
              property.area) LIKE '%txtSearchField%'

这应该适合你。

【讨论】:

    【解决方案2】:

    在这个 SQL 查询构造中,无论txtSearchField 的值是多少(即使它是空的),您都会执行它。您还忘记在变量txtSearchField 前面加上美元符号$,这就是为什么您无法从输入表单中得到任何结果,因为您总是搜索文本txtSearchField,而不是变量$txtSearchField 的内容。 (我猜你使用了一个名为txtSearchField 的带有HTML 文本输入的输入表单。)请记住将 HTML 表单的方法设置为“post”,因为如果省略它,则默认为“get”。

    如果我是对的,你应该这样修改你的代码:

        <?php
        //Sanitize user input
        $txtSearchField = filter_var($_POST['txtSearchField'], FILTER_SANITIZE_STRING);
        //SQL query
        $query = "SELECT property.propertyid, property.propertyname
        FROM   property
        WHERE  CONCAT(property.address_1, ' ',
                      property.address_2, ' ',
                      property.postcode, ' ',
                      property.area) LIKE '%$txtSearchField%'" //see the $ sign here
    //Finally, execute query and get result
    $result = mysql_query ($query) or die ('SQL error occured: '.mysql_error());
    while ($array = mysql_fetch_assoc($result)) {
      echo $result['address_1'].'/'.$result['address_2'].'/'.$result['postcode'].'/'.$result['area'].'<br/>';
    }
        ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-25
      • 2013-11-14
      • 1970-01-01
      • 2017-07-10
      • 2022-01-09
      相关资源
      最近更新 更多