konten dinamis menggunakan codeigniter

12
KONTEN DINAMIS DENGAN MENGGUNAKAN PHP FRAMEWORK CODEIGNITER (CI) 1. Buat database untuk berita, kemudian isi beberapa record. Query untuk membuat tabel seperti gambar adalah sebagai berikut CREATE TABLE 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) ); Gambar 1. Struktur Tabel News dengan menggunakan PHPMyAdmin

Upload: aku-gokiel

Post on 18-Jul-2016

94 views

Category:

Documents


11 download

DESCRIPTION

belajar membuat konten dinamis menggunakan php framework codeigniter. semoga bermanfaat.

TRANSCRIPT

Page 1: Konten Dinamis Menggunakan CodeIgniter

KONTEN DINAMIS DENGAN MENGGUNAKAN PHP

FRAMEWORK CODEIGNITER (CI)

1. Buat database untuk berita, kemudian isi beberapa record.

Query untuk membuat tabel seperti gambar adalah sebagai berikut CREATE TABLE 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)

);

Gambar 1. Struktur Tabel News dengan menggunakan PHPMyAdmin

Page 2: Konten Dinamis Menggunakan CodeIgniter

2. Konfigurasikan CI agar dapat berkomunikasi dengan database (MySQL)

Backup file “database.php” menjadi “(Backup Original) database.php” terlebih dahulu

kemudian edit file “database.php” yang berada pada direktori

“C:\xampp\htdocs\ci\application\config”. Langkah backup menurut saya pribadi perlu

dilakukan dari hal sepele dan kecil, karena mengingat dampak diwaktu yang akan datang bila terjadi

suatu disaster. Sepele semisal file tidak sengaja terhapus.

Gambar 2. File database.php yang telah dibackup

Isi dari file database sebelum diedit adalah seperti dibawah ini, perhatikan bagian highlight

berwarna hitam dari kedua listing dibawah ini : <?php if ( ! defined('BASEPATH')) exit('No direct script access

allowed');

/*

| -------------------------------------------------------------------

| DATABASE CONNECTIVITY SETTINGS

| -------------------------------------------------------------------

| This file will contain the settings needed to access your database.

|

| For complete instructions please consult the 'Database Connection'

| page of the User Guide.

|

| -------------------------------------------------------------------

| EXPLANATION OF VARIABLES

Page 3: Konten Dinamis Menggunakan CodeIgniter

| -------------------------------------------------------------------

|

| ['hostname'] The hostname of your database server.

| ['username'] The username used to connect to the database

| ['password'] The password used to connect to the database

| ['database'] The name of the database you want to connect to

| ['dbdriver'] The database type. ie: mysql. Currently supported:

mysql, mysqli, postgre, odbc, mssql, sqlite, oci8

| ['dbprefix'] You can add an optional prefix, which will be added

| to the table name when using the Active Record

class

| ['pconnect'] TRUE/FALSE - Whether to use a persistent connection

| ['db_debug'] TRUE/FALSE - Whether database errors should be displayed.

| ['cache_on'] TRUE/FALSE - Enables/disables query caching

| ['cachedir'] The path to the folder where cache files should be stored

| ['char_set'] The character set used in communicating with the database

| ['dbcollat'] The character collation used in communicating with the

database

| NOTE: For MySQL and MySQLi databases, this setting

is only used

| as a backup if your server is running PHP < 5.2.3 or

MySQL < 5.0.7

| (and in table creation queries made with DB Forge).

| There is an incompatibility in PHP with

mysql_real_escape_string() which

| can make your site vulnerable to SQL injection if

you are using a

| multi-byte character set and are running versions

lower than these.

| Sites using Latin-1 or UTF-8 database character set

and collation are unaffected.

| ['swap_pre'] A default table prefix that should be swapped with the

dbprefix

| ['autoinit'] Whether or not to automatically initialize the database.

| ['stricton'] TRUE/FALSE - forces 'Strict Mode' connections

| - good for ensuring strict SQL

while developing

|

| The $active_group variable lets you choose which connection group to

| make active. By default there is only one group (the 'default' group).

|

| The $active_record variables lets you determine whether or not to load

| the active record class

*/

$active_group = 'default';

$active_record = TRUE;

$db['default']['hostname'] = 'localhost';

$db['default']['username'] = '';

$db['default']['password'] = '';

$db['default']['database'] = '';

$db['default']['dbdriver'] = 'mysql';

$db['default']['dbprefix'] = '';

$db['default']['pconnect'] = TRUE;

$db['default']['db_debug'] = TRUE;

$db['default']['cache_on'] = FALSE;

Page 4: Konten Dinamis Menggunakan CodeIgniter

$db['default']['cachedir'] = '';

$db['default']['char_set'] = 'utf8';

$db['default']['dbcollat'] = 'utf8_general_ci';

$db['default']['swap_pre'] = '';

$db['default']['autoinit'] = TRUE;

$db['default']['stricton'] = FALSE;

/* End of file database.php */

/* Location: ./application/config/database.php */

Kemudian isi dari file database yang telah disesuaikan adalah : <?php if ( ! defined('BASEPATH')) exit('No direct script access

allowed');

/*

| -------------------------------------------------------------------

| DATABASE CONNECTIVITY SETTINGS

| -------------------------------------------------------------------

| This file will contain the settings needed to access your database.

|

| For complete instructions please consult the 'Database Connection'

| page of the User Guide.

|

| -------------------------------------------------------------------

| EXPLANATION OF VARIABLES

| -------------------------------------------------------------------

|

| ['hostname'] The hostname of your database server.

| ['username'] The username used to connect to the database

| ['password'] The password used to connect to the database

| ['database'] The name of the database you want to connect to

| ['dbdriver'] The database type. ie: mysql. Currently supported:

mysql, mysqli, postgre, odbc, mssql, sqlite, oci8

| ['dbprefix'] You can add an optional prefix, which will be added

| to the table name when using the Active Record

class

| ['pconnect'] TRUE/FALSE - Whether to use a persistent connection

| ['db_debug'] TRUE/FALSE - Whether database errors should be displayed.

| ['cache_on'] TRUE/FALSE - Enables/disables query caching

| ['cachedir'] The path to the folder where cache files should be stored

| ['char_set'] The character set used in communicating with the database

| ['dbcollat'] The character collation used in communicating with the

database

| NOTE: For MySQL and MySQLi databases, this setting

is only used

| as a backup if your server is running PHP < 5.2.3 or

MySQL < 5.0.7

| (and in table creation queries made with DB Forge).

| There is an incompatibility in PHP with

mysql_real_escape_string() which

| can make your site vulnerable to SQL injection if

you are using a

| multi-byte character set and are running versions

lower than these.

| Sites using Latin-1 or UTF-8 database character set

and collation are unaffected.

Page 5: Konten Dinamis Menggunakan CodeIgniter

| ['swap_pre'] A default table prefix that should be swapped with the

dbprefix

| ['autoinit'] Whether or not to automatically initialize the database.

| ['stricton'] TRUE/FALSE - forces 'Strict Mode' connections

| - good for ensuring strict SQL

while developing

|

| The $active_group variable lets you choose which connection group to

| make active. By default there is only one group (the 'default' group).

|

| The $active_record variables lets you determine whether or not to load

| the active record class

*/

$active_group = 'default';

$active_record = TRUE;

$db['default']['hostname'] = 'localhost';

$db['default']['username'] = 'root';

$db['default']['password'] = '';

$db['default']['database'] = 'ci';

$db['default']['dbdriver'] = 'mysql';

$db['default']['dbprefix'] = '';

$db['default']['pconnect'] = TRUE;

$db['default']['db_debug'] = false;

$db['default']['cache_on'] = FALSE;

$db['default']['cachedir'] = '';

$db['default']['char_set'] = 'utf8';

$db['default']['dbcollat'] = 'utf8_general_ci';

$db['default']['swap_pre'] = '';

$db['default']['autoinit'] = TRUE;

$db['default']['stricton'] = FALSE;

/* End of file database.php */

/* Location: ./application/config/database.php */

Iya, betul, ini adalah parameter CI dalam berkomunikasi dengan MySQL, sesuaikan nilai – nilai

parameter dengan lingkungan lokal masing – masing.

Page 6: Konten Dinamis Menggunakan CodeIgniter

3. Buat file baru dan simpan dengan nama “news_model.php” kemudian simpan pada direktori

“C:\xampp\htdocs\ci\application\models”. Tambahkan kode berikut pada file

“news_model.php”. <?

class News_model extends CI_Model

{

public function __construct()

{

$this->load->database();

}

}

Gambar 2. file news_model.php pada direktori application\models

Page 7: Konten Dinamis Menggunakan CodeIgniter

Gambar 3. News_model.php

Langkah - langkah yang tadi baru saja dilakukan adalah langkah – langkah dalam menyiapkan

database, tabel dan model dalam CI, dimana record – record yang sudah kita buat sebelumnya pada

database nanti akan ditampilkan di browser. Agar hal tersebut dapat terjadi diperlukan suatu

metode untuk menampilkan record – record dari database yang telah dibuat dengan cara

menambahkan kode berikut ini kedalam file “news_model.php”. 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();

}

File news_model yang telah ditambahkan metode get_news()

Gambar 4. File “news_model.php” yang telah ditambahkan metode “get_news()”

Page 8: Konten Dinamis Menggunakan CodeIgniter

4. Agar berita – berita tersebut dapat ditampilkan “view” sebuah controller diperlukan, cara untuk

membuat controller adalah dengan membuat file baru dengan nama “news.php” dan disimpan

pada direktori “C:\xampp\htdocs\ci\application\controllers”

Gambar 5. news.php

Kemudian tambahkan kode berikut ini pada file “news.php” <?

class News extends CI_Controller

{

public function __construct()

{

parent::__construct();

$this -> load -> model('news_model');

}

public function index()

{

$data['news'] = $this->news_model->get_news();

}

public function view($slug)

{

$data['news_item'] = $this -> news_model -> get_news($slug);

}

Page 9: Konten Dinamis Menggunakan CodeIgniter

File news.php

Gambar 6. Listing file news.php

Data berita sudah dapat ditarik dengan controller ini (news.php) tapi belum bisa ditampilkan. Agar

data tersebut dapat ditampilkan, tambahkan kode berikut ini pada metode 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');

bentuk lengkap metode public function index() menjadi seperti ini

Gambar 7. Metode public function index() yang telah ditambahkan kode

Page 10: Konten Dinamis Menggunakan CodeIgniter

5. Langkah selanjutnya adalah membuat “view” baru untuk merender item – item berita. Buatlah

sebuah file baru bernama “index.php” dan simpan di direktori

“C:\xampp\htdocs\ci\application\views\news”. Jika direktori news tidak ditemukan, maka

buatlah direktori “news”. Setelah direktori dibuat maka tambahkan kode berikut ini pada file index.php

<? foreach ($news as $news_item): ?>

<h2><? echo $news_item['title'] ?></h2>

<div id="main">

<? echo $news_item['text'] ?>

</div>

<p><a href="news/<? echo $news_item['slug'] ?>">View article</a></p>

<? endforeach ?>

Kemudian simpan file index.php dengan CTRL+S. pada bagian ini semua record ditampilkan bagi

user.

File index.php

Gambar 8. File index.php

Dengan langkah ini preview berita sudah dapat ditampilkan, tetapi untuk menampilkan berita secara

individu masih belum dapat dilakukan, agar berita secara individu dapat ditampilkan maka perlu

dibuat sebuah metode untuk menampilkan berita secara individu dengan menambahkan kode

berikut ini. Kode berikut ini ditambahkan pada file news.php yang telah dibuat sebelumnya pada

direktori “C:\xampp\htdocs\ci\application\controllers”.

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');

Page 11: Konten Dinamis Menggunakan CodeIgniter

Review gambar dibawah ini agar memudahkan.

Gambar 9. File news.php yang telah ditambahkan.

6. Lalu tambahkan kode berikut ini pada file baru bernama “view.php” <?

echo '<h2>'.$news_item['title'].'</h2>';

echo $news_item['text'];

Gambar 10. File view.php

Page 12: Konten Dinamis Menggunakan CodeIgniter

7. Pointing/routing dilakukan pada file “routes.php” pada direktori

“C:\xampp\htdocs\ci\application\config” kemudian tambahkan kode berikut ini $route['news/(:any)'] = 'news/view/$1';

$route['news'] = 'news';

$route['(:any)'] = 'pages/view/$1';

$route['default_controller'] = 'pages/view';

Gambar 11. File routes.php

8. Jalankan di web browser link berikut ini http://localhost/ci/index.php/news. jika terjadi

error. silahkan merujuk ke user_guide section codeigniter.