Insert Select Update Delete Data pada CodeIgniter dengan Query Builder

Query Builder adalah class pada CodeIgniter untuk bekerja dengan Database. Dengan Query Builder, kita dapat melakukan perintah Insert, Select, Update & Delete dengan query yang minimal.

Berikut adalah beberapa contoh penggunaan Query Builder :

Select

$query = $this->db->get('mytable');  // Produces: SELECT * FROM mytable

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

// Executes: SELECT * FROM mytable LIMIT 20, 10
// (in MySQL. Other databases have slightly different syntax)

$query = $this->db->get('mytable');
foreach ($query->result() as $row)
{
        echo $row->title;
}

Insert

$data = array(
        'title' => 'My title',
        'name' => 'My Name',
        'date' => 'My date'
);
$this->db->insert('mytable', $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')

$data = array(
        'title' => 'My title',
        'name'  => 'My Name',
        'date'  => 'My date'
);

$sql = $this->db->set($data)->get_compiled_insert('mytable');
echo $sql;

// Produces string: INSERT INTO mytable (`title`, `name`, `date`) VALUES ('My title', 'My name', 'My date')

Update

$data = array(
        'title' => 'My title',
        'name'  => 'My Name',
        'date'  => 'My date'
);
$this->db->replace('table', $data);

$this->db->set('name', $name);
$this->db->insert('mytable');  // Produces: INSERT INTO mytable (`name`) VALUES ('{$name}'

Delete

$this->db->delete('mytable', array('id' => $id));  // Produces: // DELETE FROM mytable  // WHERE id = $id

Semoga Bermanfaat !