2011-09-18 177 views
1

我有兩個表格書籍和作者。使用CodeIgniter我希望用戶能夠過濾結果 - 例如,顯示author_id ='x'和book_lang ='y'和publication_year ='2000'的結果。過濾條件值來自用戶通過下拉菜單。使用CodeIgniter過濾結果

什麼是使用codeigniter助手和綁定等生成查詢的最佳方式?例如,下面的查詢將給我author_id = 1的所有內容。例如,如果過濾器是混合的,那麼該怎麼辦? author_id = 1; language ='all'(不要把where子句放在語言上)和publication year ='all'也不要放在where子句中。我是否需要手動檢查值和代碼或者是否有一個codigniter幫助器方法,允許如果下拉值爲'全部顯示',則將從where子句中刪除過濾器?

$sql = "select * from AUTHORs a , BOOKS b where 
     a.AUTH_ID = b.BOOK_AUTH_ID 
     and b.BOOK_AUTH_ID = ? 
     and b.BOOK_LANGUAGE = ? 
     and b.PUB_YEAR = ? "; 

$query = $this->db->query($sql, array ($author_id, $book_lang, $pub_year)); 

回答

3

您應該使用笨的Active Record類來構建你的查詢:

$this->db->select('*'); 
$this->db->from('AUTHORs a , BOOKS b'); 
$this->db->where('a.AUTH_ID', 'b.BOOK_AUTH_ID'); 

if ($author_id != 'all') $this->db->where('b.BOOK_AUTH_ID', $author_id); 
if ($book_lang != 'all') $this->db->where('b.BOOK_LANGUAGE', $book_lang); 
if ($pub_year != 'all') $this->db->where('b.PUB_YEAR', $pub_year); 

$query = $this->db->get(); 

想了解更多關於笨的Active Record類,請訪問文檔:
http://codeigniter.com/user_guide/database/active_record.html