2016-10-04 82 views
2

我想用兩個下拉框來搜索我的數據庫。 ($ k)服務和($ t)鎮。但只有一個術語是工作我也是新的PHP。我知道我知道使用mysqli我只是想讓它工作並稍後更新。PHP - 使用兩個下拉菜單中的兩個搜索詞進行搜索

$k = $_GET['k']; 
$t = $_GET['t']; 

$i = 0; 
$term1 = explode(" ", $k); 
$term2 = explode(" ", $t); 

$result = array_merge($term1, $term2); 

$query ="SELECT * FROM clients WHERE "; 

foreach ($result as $each) { 
    $i++; 
    if ($i == 1) 
     $query .= "company_services LIKE '%$each%'" . "OR town LIKE '%$each%'"; 
} 
[email protected]_connect($mysql_host, $mysql_user, $mysql_password); 
$db = mysql_select_db('db_name'); 

$query = mysql_query($query) or die(mysql_error());; 
$numrows = mysql_num_rows($query); 
if ($numrows > 0){ 

    while ($row = mysql_fetch_assoc($query)) { 
+0

您可以直接使用'company_services LIKE'%$ term1%''。「或鎮LIKE'%$ term2%'''而不是使foreach複雜化,因爲它似乎只循環一次 – jitendrapurohit

回答

3

也許這樣的事情可能會奏效?

if(isset($_GET['k'], $_GET['t'])){ 

    $term1 = explode(" ", $_GET['k']); 
    $term2 = explode(" ", $_GET['t']); 

    $result = array_merge($term1, $term2); 
    $clauses=array(); 

    $query ="select * from `clients`"; 

    foreach($result as $word) { 
     $clauses[]="(`company_services` like '%$word%' OR `town` like '%$word%')"; 
    } 

    $query = !empty($clauses) ? $query . ' where ' . implode(' or ',$clauses) : $query; 


    [email protected]_connect($mysql_host, $mysql_user, $mysql_password); 
    $db = mysql_select_db('db_name'); 

    $query = mysql_query($query) or die(mysql_error()); 
    $numrows = mysql_num_rows($query); 


    if ($numrows > 0){ 
     while ($row = mysql_fetch_assoc($query)) { 
      /* do stuff*/ 
     } 
    } 
} 
0

$result = array_merge($term1, $term2);
這將設置$導致對值的數組。目前,您只是使用$ result-array的第一個值。您的foreach循環改成這樣使用所有的值:

foreach ($result as $each) { 
 
    $query .= "company_services LIKE '%$each%' OR town LIKE '%$each%' "; 
 
}