Skip to content

PHP CodeIgniter Database

Hunter Wu edited this page Jan 16, 2019 · 1 revision

Query Builder

SELECT

// SELECT * FROM mytable LIMIT 20, 10
$query = $this->db->get('mytable', 10, 20);
$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
$this->db->select('title, content, date');
$query = $this->db->get('mytable');
$this->db->select('title, content, date');
$this->db->from('mytable');
$this->db->order_by('cnt', 'DESC');
$this->db->limit(100);
$query = $this->db->get();
echo $query->num_rows();

WHERE

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

INSERT

$str = $this->db->insert_string('mytable', [
  'field1' => 'value1',
  'field2' => 'value2',
]);
echo $str, "\n\n";
$str = $this->db->insert('mytable', [
  'field1' => 'value1',
  'field2' => 'value2',
]);
  • UPDATE
$this->db->set('field', 'field+1', FALSE);
$this->db->where('id', 2);
$this->db->update('mytable');
$data = array(
        'title' => $title,
        'name' => $name,
);
$this->db->where('id', $id);
$this->db->update('mytable', $data);

Transaction

$this->db->trans_start();
# ...
$this->db->trans_complete();
Clone this wiki locally