查询mysql其中一个简单的显示特定记录

时间:2014-12-06 06:37:10

标签: php mysql

我有一个简单的房地产物业列表。我正在尝试进行一个非常简单的搜索来显示记录。例如,物业的位置,类型和价格最终。我在使用select语句时遇到问题,尤其是在用户提交空白字段时。见代码。有一个更好的方法吗?我在使用while循环显示记录的位上没问题。我是新手,我相信你可以告诉他。

<form action="search.php" method="post">

<table border="0" cellpadding="10" cellspacing="0">
<tr>
<td width="300"><b>Reference No</b></td>
<td><input type="text" name="Reference_No" maxlength="20" id="Reference_No" /></td>
</tr>

<tr>
<td><b>Property Name</b></td>
<td><input type="text" name="Property_Name" maxlength="30" id="Property_Name" /></td>
</tr>

<tr>
<td><b>Property Area</b></td>
<td>
<select name="Property_Area" id="Property_Area">
<option value="Ortaca">Ortaca</option>
<option value="Sarigerme">Sarigerme</option>
<option value="Other">Other</option>
</select>
</td>
</tr>

<tr>
<td><b>Property Type</b></td>
<td><select name="Property_Type" id="Property_Type">
<option value="Apartment">Apartment</option>
<option value="Land">Land</option>
<option value="Commercial Property">Commercial Property</option>
</select></td>
</tr>

<tr>
<td></td>
<td>
<input class="formsubmit" type="submit" value="Submit Enquiry" name="Submit" />
</td>
</tr>
</table>

</form>

$Reference_No = $_POST['Reference_No'];
$Property_Name = $_POST['Property_Name'];
$Property_Area = $_POST['Property_Area'];
$Property_Type = $_POST['Property_Type'];



$query = "SELECT * FROM properties WHERE (Live = 'yes' AND Property_Type = '$Property_Type') AND (Reference_No = '$Reference_No' OR Property_Name = '$Property_Name' OR Property_Area = '$Property_Area') ORDER BY Property_Area, Property_Price";

1 个答案:

答案 0 :(得分:0)

如果我理解正确你想要获得所有属性,如果没有选择,并限制用户选择的选择。

在SQL Server上,您可以通过以下方式使用intersect:

$filters[] = "SELECT * FROM properties"
if ($Property_Type)
    $filters[] = "SELECT * FROM properties WHERE Property_Type = '$Property_Type'";
if ($Reference_No)
    $filters[] = "SELECT * FROM properties WHERE Reference_No = '$Reference_No'";
if ($Property_Name)
    $filters[] = "SELECT * FROM properties WHERE Property_Name = '$Property_Name'";
if ($Property_Area)
    $filters[] = "SELECT * FROM properties WHERE Property_Area = '$Property_Area'";

$final_query = implode(' INTERSECT ', $filters)

但MySQL不支持INTERSECT。在这种情况下,您可以通过过滤器将过滤器包裹在过滤器上......等等

$sql = 'SELECT * FROM properties';
if ($Property_Type) 
    $sql = "SELECT * FROM ({$sql}) AS Q WHERE Property_Type = '$Property_Type'";
if ($Reference_No) 
    $sql = "SELECT * FROM ({$sql}) AS Q WHERE Reference_No = '$Reference_No'";
if ($Property_Name) 
    $sql = "SELECT * FROM ({$sql}) AS Q WHERE Property_Name = '$Property_Name'";
if ($Property_Area) 
    $sql = "SELECT * FROM ({$sql}) AS Q WHERE Property_Area = '$Property_Area'";

是的,在将它们插入查询字符串或使用参数化查询PDO或MySqli样式之前,不要忘记转义/清理所有值。