使用CodeIgniter过滤结果

时间:2011-09-18 08:56:52

标签: codeigniter filter

我有两本书和作者。使用CodeIgniter我希望用户能够过滤结果 - 例如,显示结果,其中author_id ='x'和book_lang ='y'和publication_year ='2000'。过滤条件值来自用户的下拉菜单。

使用codeigniter helper和binding等生成查询的最佳方法是什么?

例如,下面的查询将为我提供author_id = 1的所有内容。例如,如果过滤器是混合的话,该怎么办? author_id = 1; language ='all'(不要把where子句放在语言上)和publication year ='all'也不要放where where子句。我手动需要检查值和代码吗?还是有一个codigniter helper方法允许如果下拉值为'show all',则从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));

1 个答案:

答案 0 :(得分:3)

您应该使用Codeigniter的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();

要阅读有关Codeigniter的Active Record课程的更多信息,请访问文档:
http://codeigniter.com/user_guide/database/active_record.html