Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/263.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用PHP在MySQL中搜索多个列_Php_Mysql_Search - Fatal编程技术网

使用PHP在MySQL中搜索多个列

使用PHP在MySQL中搜索多个列,php,mysql,search,Php,Mysql,Search,我在互联网上搜索了很多不同的方法,但都找不到我问题的答案。我正在自学网站开发,并试图创建一个在线房地产网站 当我试图搜索某个属性时,问题就出现了。例如,我想搜索特定区域或邮政编码中的所有属性。当我尝试搜索多个字段时,如地址行1、地址行2、邮政编码和区域(如伦敦SW1V) 以下是我当前使用的查询,希望能将其更改为我需要的工作方式: SELECT property.propertyid, property.propertyname FROM property WHERE property.ad

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

当我试图搜索某个属性时,问题就出现了。例如,我想搜索特定区域或邮政编码中的所有属性。当我尝试搜索多个字段时,如地址行1、地址行2、邮政编码和区域(如伦敦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%'

这不是一种有效的方式,但对于低流量页面来说,这是最简单、最好的方式:

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

这应该适用于您。

在这个SQL查询构造中,无论
txtSearchField的值是多少(即使它是空的),您都会执行它。您还忘了在变量
txtSearchField
前面加上美元符号$,这就是为什么您无法从输入表单中获得任何结果,因为您总是搜索文本
txtSearchField
,而不是变量
$txtSearchField
的内容。(我猜您使用了一个带有HTML文本输入的输入表单,称为
txtSearchField
)。记住将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/>';
}
    ?>

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