开发者

code igniter queries: how to build this query

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 id开发者_如何学Pythoneas?


$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.


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); 


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.


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.


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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜