Monday, January 6, 2014

Codeigniter Active Record

Selecting Data

$query = $this->db->get('mytable');
$query = $this->db->get('mytable', 10, 20); 

$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset)

Select Field
$this->db->select('title, content, date');
$query = $this->db->get('mytable');


Select Max 
$this->db->select_max('age');
$query = $this->db->get('members');
// Produces: SELECT MAX(age) as age FROM members






 $this->db->select_max('age', 'member_age');
$query = $this->db->get('members');
// Produces: SELECT MAX(age) as member_age FROM members


Select Min
$this->db->select_min('age');
$query = $this->db->get('members');
// Produces: SELECT MIN(age) as age FROM members


Select AVG
$this->db->select_avg('age');
$query = $this->db->get('members');
// Produces: SELECT AVG(age) as age FROM members


Select From
$this->db->select('title, content, date');
$this->db->from('mytable');
$query = $this->db->get();
// Produces: SELECT title, content, date FROM mytable
 
 
 


Select Join
$this->db->select('*');
$this->db->from('blogs');
$this->db->join('comments', 'comments.id = blogs.id');
$query = $this->db->get();

// Produces:
// SELECT * FROM blogs
// JOIN comments ON comments.id = blogs.id


$this->db->where();

1. Simple key/value method:  
   $this->db->where('name', $name); 
2. Custom key/value method:
   $this->db->where('name !=', $name);
   $this->db->where('id <', $id);
   // Produces: WHERE name != 'Joe' AND id < 45 

3.Associative array method:
  $array = array('name' => $name, 'title' => $title, 'status' => $status);
  $this->db->where($array);
// Produces: WHERE name = 'Joe' AND title = 'boss' AND status = 'active' 

  atau
  $array = array('name !=' => $name, 'id <' => $id, 'date >' => $date);
  $this->db->where($array);
 

4.Custom string:
  $where = "name='Joe' AND status='boss' OR status='active'";
  $this->db->where($where);


 

No comments:

Post a Comment