我有两个表图书和作者。使用CodeIgniter,我希望用户能够过滤结果-例如,显示author_id = 'x'和book_lang = 'y'和publication_year = '2000'的结果。过滤标准值通过下拉菜单来自用户。
使用codeigniter helper和绑定等生成查询的最佳方法是什么?
例如,下面的查询将为我提供author_id= 1的所有内容。例如,如果过滤器是混合的呢?Author_id = 1;语言= 'all'(不要在语言上加上where子句),出版年份= 'all'也不要加上where子句。我是否需要手动检查值和代码,或者是否有一个codigniter helper方法,允许从子句中删除过滤器,如果下拉值是"显示全部"?
$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));
您应该使用Codeigniter的活动记录类来构造您的查询:
$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的活动记录类,请访问文档:
http://codeigniter.com/user_guide/database/active_record.html