简体   繁体   中英

How do I convert a MySQL query to codeigniter active records?

I`m new to codeigniter and I would like to convert following MySQL query into Codeigniter Active Record Queries.

MySQL Query:

select sevadar_id, sevadar_name from tbl_sevadarmaster where  
sevadar_designation = 6 and sevadar_id not in (SELECT p_id FROM  
`tbl_events` WHERE program_id = 27 and event_date = 2014-07-06 and p_id is not null)

CodeIgniter has really good docs for their entire API I'd highly suggest giving them a quick read. Specifically regarding your question you should have a look at the Active Record docs here and at the CodeIgniter query library , which will give you tips on producing safer queries using the API. Together, these two links contain all the API calls you'll need to build your query in CodeIgniter.

At the very simplest level you could do:

$query = $this->db->query('select sevadar_id, sevadar_name from tbl_sevadarmaster where sevadar_designation = 6 and sevadar_id not in (SELECT p_id FROM `tbl_events` WHERE program_id = 27 and event_date = 2014-07-06 and p_id is not null)');

But you'll want to use query bindings (see the very bottom of the query libraries page) to auto escape data producing safer queries, here's an example of using query bindings from that page of the API:

$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?"; 
$this->db->query($sql, array(3, 'live', 'Rick'));

If you use the Active Record library you can try:

$this->db->select('p_id');
$this->db->from('tbl_events');
$this->db->where('program_id', 27);
$this->db->where('event_date', '2014-07-06');
$this->db->where('p_id is not', null);
$where_clause = $this->db->get_compiled_select();

$this->db->select('sevadar_id, sevadar_name');
$this->db->from('tbl_sevadarmaster');
$this->db->where('sevadar_designation', 6);
$this->db->where("`sevadar_id` NOT IN ($where_clause)", NULL, FALSE);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM