2009-09-15 28 views
1

我試圖創建一個簡單的搜索頁面,但我不是100%確定如何編寫實際的搜索字符串(使用適當和的等如果變量存在)下面的代碼:動態創建一個mysql搜索字符串?

if ($post) { 

    //get all search variables 
    $type = JRequest::getVar('type'); 
    $classifications = JRequest::getVar('classifications', array(0), 'post', 'array'); 
    $rating = JRequest::getVar('rating'); 
    $status = JRequest::getVar('status'); 
    $cterms = JRequest::getVar('cterms'); 
    $clientid = JRequest::getVar('clientid'); 
    $company = JRequest::getVar('company'); 
    $address = JRequest::getVar('address'); 
    $name = JRequest::getVar('name'); 
    $surname = JRequest::getVar('surname'); 
    $city = JRequest::getVar('city'); 
    $state = JRequest::getVar('state'); 
    $pcode = JRequest::getVar('pcode'); 
    $country = JRequest::getVar('country'); 

    //create search string 
    echo "SELECT * FROM #__db_clients "; <- the query is supposed to be done here.. it's in as echo because I was trying to spit it out before trying to make it run.. :) 

} else { 

    echo 'There has been an error, please try again.'; 

}; 

我已經嘗試使用(如果type!= null,則檢索類別=「其中type =‘X’」),但我無法弄清楚如何放置和/後,如果之前它需要的搜索..如果讓感?

回答

2

這是一個簡單的例子。我不知道JRequest :: getVar返回的是什麼樣的數據(總是一個字符串或混合類型?),但是這應該讓你開始。請確保在foreach循環中使用適用的轉義方法:

if ($post) { 
    $criteria = array(); 
    //get all search variables 
    $criteria['type'] = JRequest::getVar('type'); 
    $criteria['classifications'] = JRequest::getVar('classifications', array(0), 'post', 'array'); 
    $criteria['rating'] = JRequest::getVar('rating'); 

    //if there are some criteria, make an array of fieldName=>Value maps 
    if(!empty($criteria)) { 
     $where = array(); 
     foreach($criteria as $k => $v) { 
      //IMPORTANT!! 
      //$v is the value of the field, needs to be quoted correctly!! 
      $where[] = "$k = '$v'"; 
     } 
    } 
    //create search string 
    $query = "SELECT * FROM #__db_clients"; 

    if($where) { 
     $query .= " where " . join(' AND ', $where); 
    } 
} else {  
    echo 'There has been an error, please try again.'; 
}; 
+2

將內容插入到表達式中時,一定要將轉義應用於'$ v'。 – 2009-09-15 01:36:53

+1

@ Bill Karwin - 絕對謝謝!我不知道哪個轉義方法適用於他的應用程序,所以我在答案中寫了一個註釋(以及代碼註釋)。 – karim79 2009-09-15 01:40:32

+0

非常感謝,這肯定會幫助我得到我的代碼:)非常感謝! – SoulieBaby 2009-09-15 01:42:31