2013-05-30 172 views
-1

我有一個產品的MySQL表添加了超過6個服務(列)。如何選擇具有多個值匹配的mysql行匹配

那些列,你可以考慮爲service1, service2, service3, service4, service5, service6

現在我的網頁上顯示的數據表。要過濾該表相應的服務我使用的表單包括每個服務的複選框。

每個複選框有value = "Yes"

現在,當我選擇的服務和按下提交按鈕,它會刷新頁面,經過查詢參數這樣

page.php?service1=Yes&service2=Yes&service3=&service4=&service5=Yes&service6= 

這裏的服務是坯料意味着我沒有從表格中選擇,所以他們在這裏空白。如果我選擇它們,它會得到Yes值。

我想選擇服務的表格行是否有「是」值。並忽略那些沒有值的值。

該怎麼辦?

+0

這是非常簡單的一個WHERE子句。你嘗試過什麼嗎? – enenen

+0

在問這裏之前,請自己嘗試解決您的問題。如果你因爲不明白問題所在而無法進展,那就問問。但這意味着你可以提出一個具體的問題,而不是像「我怎麼能編程什麼東西」...... – arkascha

+0

是的,但如果查詢參數沒有值,我想忽略它。如果service1 =是,service2不是= yes或空白,則不會放在WHERE子句 –

回答

1

我正在寫一個答案,但請儘量詢問下一次前做出一些努力:

HTML:

<form name="form" method="get" action=""> 
    Service 1: <input type="checkbox" name="service1"/><br/> 
    Service 2: <input type="checkbox" name="service2"/><br/> 
    Service 3: <input type="checkbox" name="service3"/><br/> 
    Service 4: <input type="checkbox" name="service4"/><br/> 
    Service 5: <input type="checkbox" name="service5"/><br/> 
    Service 6: <input type="checkbox" name="service6"/><br/><br/> 
    <input type="submit" value="Search" name="submit"/> 
</form> 

PHP:

if(isset($_GET['submit'])) { // If the form is submitted 
    $services = array(); // Define an empty array 

    for($i = 1; $i<=6; $i++) { 
     if($_GET["service$i"]) { // If Service(x) checkbox is checked 
      $services[] = "service$i = 'Yes'"; // Add to array 
     } 
    } 

    if(count($services) > 0) { 
     print_r($services); // Here are all choosed services 

     $selectQuery = "SELECT * FROM products WHERE " . implode(' AND ', $services) . ";"; 
     // Take a look what implode function does: http://php.net/manual/en/function.implode.php 

     echo $selectQuery; // Now fetch the result using this query 
    } else { 
     // There is not any service checked. Maybe you can just get all the information from the table in this case. 
    } 
} 
0

你意味着檢查你想檢查一些字段是空白的,有些是'是'?

如果是的話是這樣的: -

<?php 

$RequiredVars = array('service1'=>'Yes','service2'=>'Yes','service3'=>'Yes','service4'=>'Yes','service5'=>'Yes','service6'=>'Yes'); 

$Clause = array(); 
foreach($_REQUEST AS $Field=>$Value) 
{ 
    if (array_key_exists($Field, $RequiredVars)) 
    { 
     $Clause[] = " $Field = '".mysql_real_escape_string($Value)."' "; 
    } 
} 

$sql = "SELECT * FROM SomeTable "; 

if (count($Clause) > 0) 
{ 
    $sql .= "WHERE ".implode(' AND ', $Clause); 
} 

?>