2012-02-09 29 views
1

這裏一個搜索是我的PHP代碼:如何搜索多個列使用多輸入

if (($_REQUEST['Search']) || ($_REQUEST['CSV'])){ 
$street = $_REQUEST['street']; 
$zip = $_REQUEST['zip']; 
$city = $_REQUEST['city']; 
$type = $_REQUEST['type']; 
if ($_REQUEST['street']){ 
    $q = " SELECT * FROM $usertable WHERE address LIKE '%$street%' ORDER BY address "; 
} 
if ($_REQUEST['zip']){ 
    $q = " SELECT * FROM $usertable WHERE zip LIKE '%$zip%' ORDER BY address "; 
} 
if ($_REQUEST['city']){ 
    $q = " SELECT * FROM $usertable WHERE city LIKE '%$city%' ORDER BY address "; 
} 
$qu = mysql_query($q); 

這裏是我的html:

<form action="" method="post"> 
Zip:<input name="zip" type="text" /> 
Street:<input name="street" type="text" /> 
City:<input name ="city" type="text" /> 
Type:<select id="type" name="type"> 
<option value="Invasion">Invasion</option> 
<option value="Burglary">Burglary</option> 
<option value="Theft">Theft</option> 
</select> 
<input name="Search" type="submit" value="Search" /> 
<input name="CSV" type="submit" value="Get CSV" /> 
</form> 

我試圖做的是有我的網站可以使用城市郵編或街道的任意組合進行搜索。我相信我必須連接或者其他東西,但作爲後院程序員,我有點難住。謝謝!

+0

你怎麼看你的查詢? – sinsedrix 2012-02-09 18:25:57

回答

2

爲了得到它在1查詢(未測試);

<?php 

    $q = " SELECT * FROM ". $usertable ." WHERE 1 %s ORDER BY address "; 

    if ($_REQUEST['street']){ 
     $where[] = " address LIKE '%".$street."%' "; 
    } 
    if ($_REQUEST['zip']){ 
     $where[] = " zip LIKE '%".$zip."%' "; 
    } 
    if ($_REQUEST['city']){ 
     $where[] = " city LIKE '%".$city."%' "; 
    } 

    $q = sprintf($q, implode(" AND ", $where)); 

    echo $q; 
1

下面是如何根據您定義的字段生成查詢搜索的示例。 搜索將僅在具有值的字段上執行,並且查詢是安全的(值被轉義,因此您不必擔心SQL注入)。

我添加代碼中的註釋

<?php 
if (($_REQUEST['Search']) || ($_REQUEST['CSV'])){ 

$conditions = array(); 
// define the fields that are searchable (we assumed that the table field names match the form input names) 
$search_fields = array('street', 'zip', 'city', 'type'); 
foreach($search_fields as $field) { 
    // if the field is set and it is not empty 
    if (isset($_REQUEST[$field]) && strlen($_REQUEST[$field]) > 0){ 
     // escape the value 
     $conditions[] = "`$field` LIKE '%". mysql_real_escape($field) ."%'"; 
    } 
} 

$q = "SELECT * FROM $usertable "; 

// if there are conditions defined 
if(count($conditions) > 0) 
{ 
    // concatenate them and append to the query 
    // we use operator AND to retrieve results that match all defined criteria 
    $q .= "WHERE ". implode(" AND ", $conditions); 
} 

$qu = mysql_query($q);