Kali ini kita akan membuat aplikasi berbasis website menggunakan CodeIgniter 3
- Pertama buat database dengan tabel students seperti ini
- Ubah Database.php dalam folder config untuk menghubungkan aplikasi ke database
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$active_group = 'default';
$query_builder = TRUE;
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'pbkk_crud',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
- Buat model untuk students
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Student_model extends CI_Model
{
private $_table = "students";
public $id;
public $name;
public $gender;
public $birthplace;
public $birthdate;
public $address;
public $phone;
public function rules()
{
return [
['field' => 'name',
'label' => 'Name',
'rules' => 'required'],
['field' => 'gender',
'label' => 'Gender',
'rules' => 'required'],
['field' => 'birthplace',
'label' => 'Birthplace',
'rules' => 'required'],
['field' => 'birthdate',
'label' => 'Birthdate',
'rules' => 'required'],
['field' => 'address',
'label' => 'Address',
'rules' => 'required'],
['field' => 'phone',
'label' => 'Phone',
'rules' => 'required']
];
}
public function getAll()
{
return $this->db->get($this->_table)->result();
}
public function getById($id)
{
return $this->db->get_where($this->_table, ["id" => $id])->row();
}
public function create()
{
$post = $this->input->post();
$this->id = uniqid();
$this->name = $post["name"];
$this->gender = $post["gender"];
$this->birthplace = $post["birthplace"];
$this->birthdate = $post["birthdate"];
$this->address = $post["address"];
$this->phone = $post["phone"];
return $this->db->insert($this->_table, $this);
}
public function update()
{
$post = $this->input->post();
$this->id = $post["id"];
$this->name = $post["name"];
$this->gender = $post["gender"];
$this->birthplace = $post["birthplace"];
$this->birthdate = $post["birthdate"];
$this->address = $post["address"];
$this->phone = $post["phone"];
return $this->db->update($this->_table, $this, array('id' => $post['id']));
}
public function delete($id)
{
return $this->db->delete($this->_table, array("id" => $id));
}
}
- Buat view untuk CRUD Data