如何获得PHP输入mysql的多重搜索


how to get multipale search input php mysql

嗨,我是新的PHP mysql。我创建了一个表单,用户可以在其中搜索数据库,结果取决于用户如何填写表单。表单有6个搜索字段。用户可以选择/填写任何一个或多个字段来进行搜索。我将其编码如下php

<?php require_once('Connections/osrc.php'); ?>
<?php
$maxRows_search_result = 10;
$pageNum_search_result = 0;
if (isset($_GET['pageNum_search_result'])) {
  $pageNum_search_result = $_GET['pageNum_search_result'];
}
$startRow_search_result = $pageNum_search_result * $maxRows_search_result;
mysql_select_db($database_osrc, $osrc);
$propertyid = $_POST['propertyid'];
$offered = $_POST['offered'];
$property_type = $_POST['property_type'];
$beds = $_POST['beds'];
$city = $_POST['city'];
$locality = $_POST['locality'];
$query_search_result = "SELECT * FROM osrc_data WHERE propertyid LIKE '%$propertyid%' OR offered LIKE '%$offered%' AND property_type LIKE '%$property_type%' AND beds LIKE '%$beds%' AND city LIKE '%$city%' AND locality LIKE '%$locality%' ";
$query_limit_search_result = sprintf("%s LIMIT %d, %d", $query_search_result, $startRow_search_result, $maxRows_search_result);
$search_result = mysql_query($query_limit_search_result, $osrc) or die(mysql_error());
$row_search_result = mysql_fetch_assoc($search_result);
if (isset($_GET['totalRows_search_result'])) {
  $totalRows_search_result = $_GET['totalRows_search_result'];
} else {
  $all_search_result = mysql_query($query_search_result);
  $totalRows_search_result = mysql_num_rows($all_search_result);
}
$totalPages_search_result = ceil($totalRows_search_result/$maxRows_search_result)-1;
?>

现在当用户它工作,但它显示数据库表中的所有行。例如,用户填写三个字段床,城市,地区和其余三个是空白的。搜索结果页面显示数据库中所有记录的所有行。请帮我改正我的代码。提前感谢

首先,我同意@VaaChar的观点,你应该使用mysqli或者更好的PDO。

您必须确定一个值是否已被放置在字段中,如果是,则在查询中使用它。如果在该字段中没有放置值,则在查询中忽略它。

像这样…

$sqlid = "";
$sqloffered = "";
$sqltype = "";
$sqlbeds = "";
$sqlcity = "";
$sqllocality = "";
if(isset($propertyid)) {
    $sqlid = " propertyid LIKE '%$propertyid%'";
}
if(isset($propertyid) && isset($offered)) {
    $sqloffered = " OR offered LIKE '%$offered%'"; 
}
if(!isset($propertyid) && isset($offered)) {
    $sqloffered = " offered LIKE '%$offered%'"; 
}
if(isset($property_type)) {
    $sqltype = " AND property_type LIKE '%$property_type%'";
}
if(isset($beds)) {
    $sqlbeds = " AND beds LIKE '%$beds%'";
}
if(isset($city)) {
    $sqlcity = " AND city LIKE '%$city%'";
}
if(isset($locality)) {
    $sqllocality = " AND locality LIKE '%$locality%'";
}
$sql = "SELECT * FROM osrc_data WHERE {$sqlid}{$sqloffered}{$sqltype}{$sqlbeds}{$sqlcity}{$sqllocality} ";

当您使用(例如)$propertyid为空构建sql查询时,您将得到以下结果:

…比如"%%"……

就像在说"任何事"。您必须仅使用已填充的字段构建查询。