Friday 27 October 2017
4 komentar

Membuat CRUD Sederhana Di Codeigniter


Artikel yang saya buat ini menunjukkan Bagaimana cara yang paling mudah membuat aplikasi CRUD (Create, Read, Update, Delete) sederhana dengan CodeIgniter. CodeIgniter (CI) adalah Framework PHP yang membantu membangun aplikasi web dengan lengkap.

Artikel ini merupakan kelanjutan dari tutorial dasar yang ada di situs/modul resmi CodeIgniter. Tutorial memiliki view dan add data part. Tapi, itu tidak berisi update dan delete part. Dan Saya baru saja menambahkan fungsi update dan delete di dalamnya.

Berikut adalah panduan langkah demi langkah untuk membuat aplikasi CRUD (Add / Edit / Delete / Update) di CodeIgniter.

Buat Database Dan Table

Pertama-tama, kita membuat database dan tabel. Untuk contoh artikel ini, kita akan membuat database bernama test. Dan saya akan membuat tabel bernama news di dalam database test.

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
--
-- Create database `test`
--
 
CREATE DATABASE `test`;
 
use `test`;
 
--
-- Table structure for table `news`
--
 
CREATE TABLE IF NOT EXISTS `news` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(128) NOT NULL,
  `slug` varchar(128) NOT NULL,
  `text` text NOT NULL,
  PRIMARY KEY (`id`),
  KEY `slug` (`slug`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
 
--
-- Dumping data for table `news`
--
 
INSERT INTO `news` (`id`, `title`, `slug`, `text`) VALUES
(1, 'Test', 'test', 'Hello World !!'),
(2, 'What is Lorem Ipsum?', 'what-is-lorem-ipsum', 'Lorem Ipsum is simply dummy text.');



Database Config Settings

Setelah Anda membuat database, Anda perlu menentukan host database, nama database, username database & password database Anda dalam file konfigurasi database di codeigniter. File tersebut berada pada application / config / database.php. Host database saya adalah localhost, nama database adalah tes (seperti yang dibuat oleh query sql di atas), username database adalah root dan password database adalah root. Berikut adalah pengaturan konfigurasi untuk contoh ini:

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
$db['default'] = array(
    'dsn'    => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => 'root',    
    'database' => 'test',    
    '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
);

Controller

(application/controllers/News.php)
Pertama-tama, kita memerlukan Controller yang memproses permintaan masukan dari pengguna, berkomunikasi dengan Model dan kemudian memuat file Views yang sesuai.
Di kelas Controller di bawah ini, kita memiliki function (tindakan) yang berbeda untuk berbagai tugas. Seperti, function index () digunakan untuk daftar semua item berita, function create () yang digunakan untuk menambahkan item berita baru, function edit () yang digunakan untuk mengedit item berita, dan function delete () digunakan untuk menghapus item berita


1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
<?php
class News extends CI_Controller {
 
    public function __construct()
    {
        parent::__construct();
        $this->load->model('news_model');
        $this->load->helper('url_helper');
    }
 
    public function index()
    {
        $data['news'] = $this->news_model->get_news();
        $data['title'] = 'News archive';
 
        $this->load->view('templates/header', $data);
        $this->load->view('news/index', $data);
        $this->load->view('templates/footer');
    }
 
    public function view($slug = NULL)
    {
        $data['news_item'] = $this->news_model->get_news($slug);
        
        if (empty($data['news_item']))
        {
            show_404();
        }
 
        $data['title'] = $data['news_item']['title'];
 
        $this->load->view('templates/header', $data);
        $this->load->view('news/view', $data);
        $this->load->view('templates/footer');
    }
    
    public function create()
    {
        $this->load->helper('form');
        $this->load->library('form_validation');
 
        $data['title'] = 'Create a news item';
 
        $this->form_validation->set_rules('title', 'Title', 'required');
        $this->form_validation->set_rules('text', 'Text', 'required');
 
        if ($this->form_validation->run() === FALSE)
        {
            $this->load->view('templates/header', $data);
            $this->load->view('news/create');
            $this->load->view('templates/footer');
 
        }
        else
        {
            $this->news_model->set_news();
            $this->load->view('templates/header', $data);
            $this->load->view('news/success');
            $this->load->view('templates/footer');
        }
    }
    
    public function edit()
    {
        $id = $this->uri->segment(3);
        
        if (empty($id))
        {
            show_404();
        }
        
        $this->load->helper('form');
        $this->load->library('form_validation');
        
        $data['title'] = 'Edit a news item';        
        $data['news_item'] = $this->news_model->get_news_by_id($id);
        
        $this->form_validation->set_rules('title', 'Title', 'required');
        $this->form_validation->set_rules('text', 'Text', 'required');
 
        if ($this->form_validation->run() === FALSE)
        {
            $this->load->view('templates/header', $data);
            $this->load->view('news/edit', $data);
            $this->load->view('templates/footer');
 
        }
        else
        {
            $this->news_model->set_news($id);
            //$this->load->view('news/success');
            redirect( base_url() . 'index.php/news');
        }
    }
    
    public function delete()
    {
        $id = $this->uri->segment(3);
        
        if (empty($id))
        {
            show_404();
        }
                
        $news_item = $this->news_model->get_news_by_id($id);
        
        $this->news_model->delete_news($id);        
        redirect( base_url() . 'index.php/news');        
    }
}





Model

(application/models/News_model.php)
Model kelas berkomunikasi dengan database. Logika database utama ditulis disini. Kelas ini bertanggung jawab untuk berinteraksi dengan database untuk data pilih, insert, update dan hapus tujuan.
Di bawah kelas Model, function et_news ()  berfungsi untuk fetches/selects item berita dengan nama $slug. Function get_news_by_id () mengambil berita dari ID itu. set_news () berfungsi mengedit atau menambahkan item berita. Function delete_news () menghapus item berita tertentu.



1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
class News_model extends CI_Model {
 
    public function __construct()
    {
        $this->load->database();
    }
    
    public function get_news($slug = FALSE)
    {
        if ($slug === FALSE)
        {
            $query = $this->db->get('news');
            return $query->result_array();
        }
 
        $query = $this->db->get_where('news', array('slug' => $slug));
        return $query->row_array();
    }
    
    public function get_news_by_id($id = 0)
    {
        if ($id === 0)
        {
            $query = $this->db->get('news');
            return $query->result_array();
        }
 
        $query = $this->db->get_where('news', array('id' => $id));
        return $query->row_array();
    }
    
    public function set_news($id = 0)
    {
        $this->load->helper('url');
 
        $slug = url_title($this->input->post('title'), 'dash', TRUE);
 
        $data = array(
            'title' => $this->input->post('title'),
            'slug' => $slug,
            'text' => $this->input->post('text')
        );
        
        if ($id == 0) {
            return $this->db->insert('news', $data);
        } else {
            $this->db->where('id', $id);
            return $this->db->update('news', $data);
        }
    }
    
    public function delete_news($id)
    {
        $this->db->where('id', $id);
        return $this->db->delete('news');
    }
}

Template Header

(application/views/templates/header.php)
Ini adalah file template yang umum untuk semua halaman. Saya memanggil header di semua halaman.

1
2
3
4
5
6
7
8
<html>
        <head>
                <title>CodeIgniter Tutorial</title>
        </head>
        <body>
 
                <h1>Simple CRUD</h1>
                <p><a href="<?php echo site_url('news'); ?>">Home</a> | <a href="<?php echo site_url('news/create'); ?>">Add News</a></p>


Template Footer

(application/views/templates/footer.php)
Ini adalah file template yang umum untuk semua halaman. Saya memanggil footer ini di semua halaman.



1
2
3
<p><em>Copyright © 2016</em></p>
        </body>
</html>

Index View

(application/views/news/index.php)
File view ini disebut dengan Function index() di kelas Controller kita. Ini mencantumkan semua item berita.

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<h2><?php echo $title; ?></h2>
 
<table border='1' cellpadding='4'>
    <tr>
        <td><strong>Title</strong></td>
        <td><strong>Content</strong></td>
        <td><strong>Action</strong></td>
    </tr>
<?php foreach ($news as $news_item): ?>
        <tr>
            <td><?php echo $news_item['title']; ?></td>
            <td><?php echo $news_item['text']; ?></td>
            <td>
                <a href="<?php echo site_url('news/'.$news_item['slug']); ?>">View</a> | 
                <a href="<?php echo site_url('news/edit/'.$news_item['id']); ?>">Edit</a> | 
                <a href="<?php echo site_url('news/delete/'.$news_item['id']); ?>" onClick="return confirm('Are you sure you want to delete?')">Delete</a>
            </td>
        </tr>
<?php endforeach; ?>
</table>

Detail View

(application/views/news/view.php)
File view ini disebut dengan function view () di kelas Controller kita. Ini mencetak item berita tertentu.

1
2
3
<?php
echo '<h2>'.$news_item['title'].'</h2>';
echo $news_item['text'];

Add View

(application/views/news/create.php)
File view ini disebut dengan function create () di kelas Controller kita. Ini mencetak formulir untuk menambahkan item berita.

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<h2><?php echo $title; ?></h2>
 
<?php echo validation_errors(); ?>
 
<?php echo form_open('news/create'); ?>    
    <table>
        <tr>
            <td><label for="title">Title</label></td>
            <td><input type="input" name="title" size="50" /></td>
        </tr>
        <tr>
            <td><label for="text">Text</label></td>
            <td><textarea name="text" rows="10" cols="40"></textarea></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" name="submit" value="Create news item" /></td>
        </tr>
    </table>    
</form>

Edit View

(application/views/news/edit.php)
File view ini disebut dengan function edit () dari kelas Controller kita. Ini mencetak formulir untuk mengedit item berita.

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<h2><?php echo $title; ?></h2>
 
<?php echo validation_errors(); ?>
 
<?php echo form_open('news/edit/'.$news_item['id']); ?>
    <table>
        <tr>
            <td><label for="title">Title</label></td>
            <td><input type="input" name="title" size="50" value="<?php echo $news_item['title'] ?>" /></td>
        </tr>
        <tr>
            <td><label for="text">Text</label></td>
            <td><textarea name="text" rows="10" cols="40"><?php echo $news_item['text'] ?></textarea></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" name="submit" value="Edit news item" /></td>
        </tr>
    </table>
</form>

Add Success View

(application/views/news/success.php)
File tampilan ini disebut setelah item berita baru ditambahkan ke database. File ini disebut dalam function create() di kelas Controller kita.

1
<p>News added successfully!</p>

Config Routes

(application/config/routes.php)
Aturan perutean didefinisikan di sini. Rute dapat ditentukan dengan menggunakan wildcard atau Regular Expressions.

1
2
3
4
5
6
7
$route['news'] = 'news';
$route['news/create'] = 'news/create';
 
$route['news/edit/(:any)'] = 'news/edit/$1';
 
$route['news/view/(:any)'] = 'news/view/$1';
$route['news/(:any)'] = 'news/view/$1';

Sekarang, Anda dapat mengakses aplikasi Anda sebagai http://your-website.com/news.

Saat Anda membuka proyek di browser, Anda akan mendapatkan gambar seperti gambar di bawah ini:






4 komentar :

 
Toggle Footer
Top