Kita lanjutkan mempelajari CodeIgniter dari artikel sebelumnya Menampilkan/View Data dengan Web CodeIgniter dari MySQL dan Menambah (Add) Data dengan Web PHP CodeIgniter. Kali ini kita buat halaman edit (update) data secara sederhana tanpa helper form terlebih dahulu.
Pertama tambahkan kode program di bawah ini pada Model webci/application/models/msiswa.php :
<?php
class Msiswa extends CI_Model
{
function getdata()
{
$ambil = $this->db->get('siswa');
if($ambil->num_rows() > 0)
{
foreach($ambil->result() as $baris)
{
$hasil[] = $baris;
}
return $hasil;
}
}
function simpandata(){
$nis = $this->input->post('nis');
$nama = $this->input->post('nama');
$alamat = $this->input->post('alamat');
$tgllahir = $this->input->post('tgllahir');
$nilai = $this->input->post('nilai');
$data = array(
'nis' => $nis,
'nama' => $nama,
'alamat' => $alamat,
'tgllahir' => $tgllahir,
'nilai' => $nilai
);
$this->db->insert('siswa',$data);
}
function selectdata($id){
return $this->db->get_where('siswa',array('nis'=>$id))->row();
}
function ubahdata($id){
$nis = $this->input->post('nis');
$nama = $this->input->post('nama');
$alamat = $this->input->post('alamat');
$tgllahir = $this->input->post('tgllahir');
$nilai = $this->input->post('nilai');
$data = array(
'nis' => $nis,
'nama' => $nama,
'alamat' => $alamat,
'tgllahir' => $tgllahir,
'nilai' => $nilai
);
$this->db->where('nis',$id);
$this->db->update('siswa',$data);
}
?>
Kemudian kita buat View baru webci/application/views/veditsiswa.php :
<form action="<?php echo $baris->nis; ?>" method="post">
<table>
<tr><td>NIP</td><td><input type="text" name="nis" value="<?php echo $baris->nis; ?>"></td></tr>
<tr><td>Nama</td><td><input type="text" name="nama" value="<?php echo $baris->nama; ?>"></td></tr>
<tr><td>Alamat</td><td><input type="text" name="alamat" value="<?php echo $baris->alamat; ?>"></td></tr>
<tr><td>Tgl Lahir</td><td><input type="text" name="tgllahir" value="<?php echo $baris->tgllahir; ?>"></td></tr>
<tr><td>Nilai</td><td><input type="text" name="nilai" value="<?php echo $baris->nilai; ?>"></td></tr>
<tr><td></td><td><input type="submit" name="submit" value="Simpan"></td></tr>
</table>
</form>
Terakhir kita tambahkan kode program pada Controller webci/application/controllers/siswa.php :
<?php
class Siswa extends CI_Controller{
function index(){
$this->load->model('msiswa');
$data['isi'] = $this->msiswa->getdata();
$this->load->view('vsiswa',$data);
}
function tambah()
{
if($this->input->post('submit')){
$this->load->model('msiswa');
$this->msiswa->simpandata();
redirect('siswa');
}
$this->load->view('vaddsiswa');
}
function ubah($id)
{
if($this->input->post('submit'))
{
$this->load->model('msiswa');
$this->msiswa->ubahdata($id);
redirect('siswa');
}
else
{
$this->load->model('msiswa');
$data['baris'] = $this->msiswa->selectdata($id);
$this->load->view('veditsiswa',$data);
}
}
}
?>
Hasilnya :
Kode Program Project Selengkapnya Menyusul.
Semoga berhasil :)