code igniter queries: how to build this query

我的未来我决定 提交于 2019-12-25 04:37:37

问题


I am attempting to build a query using code igniter's active records class that looks like this:

SELECT * from contacts where account = 1 and (fname like 'k%' or lname like 'k%')

however I am not sure how to use the functions to do this.

and ideas?


回答1:


You can also use the like query

$this->db->like('title', 'match');

// Produces: WHERE title LIKE '%match%' 

And or_like

$this->db->like('title', 'match');
$this->db->or_like('body', $match); 



回答2:


$this->db->where('account', '1');
$this->db->where(' (fname LIKE "k%" OR lname LIKE "k%" ) ');
$query = $this->db->get('contacts');

Then just deal with $query like a normal Codeigniter database result.




回答3:


Yo can allways run it as a normal query:

$sql = "SELECT * from contacts where account = 1 and (fname like ? or lname like ?)";
$query = $this->db->query($sql, array( $like1, $like2));

I use more often this than the active record class as I'm keen in writing sql statements.




回答4:


Instead of using normal query, you can use the suggestion from the ellislab forum https://ellislab.com/forums/viewthread/185983/ Instead of using

$this->db->like('location', $your_string);

use:

$this->db->where('location LIKE', '%'.$your_string.'%');

and or_where instead of or_like.




回答5:


You can use query grouping from CI 3.0

$this->db->select('*')->from('contacts ')
    ->group_start()
            ->like('fname', 'k', 'after');
            ->or_like('lname', 'k', 'after'); 
    ->group_end()
    ->where('account', 1)
->get();


来源:https://stackoverflow.com/questions/4855367/code-igniter-queries-how-to-build-this-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!