CodeIgniter is one of popular PHP framework that implemented MVC software architectural pattern. Different from another PHP framework, like YII and Symfony, CodeIgniter is lightweight and offer simplified code organization with small footprint. It's mean, we only add or install any external libraries as needed. In the overall, CodeIgniter framework is the best framework that must be tried for whom new on PHP framework.
CRUD is the acronym from four words: Create, Read, Update and Delete. That's four words represent the basic operation on the database; Create operation for INSERT command, Read operation for SELECT command, Update operation for UPDATE command, and Delete operation for DELETE command.
Follow the tutorial below to create simple CRUD using CodeIgniter:
STEP 1 Download CodeIgniter
Go to CodeIgniter Download Page to download compressed CodeIgniter source code. In this tutorial, i used the Codeigniter version 3.0.6. After that, extract the downloaded file to your server document's root and rename the "CodeIgniter-3.0.6" folder to your app name. In this example, the app name is myapp.
STEP 2 Build The Database
I've created the database named as test_database that has 13 tables:

If you just follow this tutorial, you can download the database here.
STEP 3 Modify The Database Configuration
Open myapp/application/config/database.php file, then modify any values corresponding to your database configuration. In this tutorial, our database configuration looked like:
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => 'mypwd',
'database' => 'test_database',
'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
);
To make every query call work, we need to ensure that CodeIgniter's database library always steady. Go to myapp/application/config/autoload.php and modify $autoload['libraries'] value.
$autoload['libraries'] = array('database');
STEP 4 Modify The Codeigniter Main Configuration
Open myapp/application/config/config.php file to modify main configuration. The most important option to be configured is Base Site URL. To modify it, look for $config['base_url'] variable and fill with:
http://localhost/myapp if you on local development server
or
http://www.myapp.com if you on production hosted server
or
http://".$_SERVER['HTTP_HOST'].str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']) if you developed in both environtment
If all good, you can get the base site URL as string by calling the base_url() function . To simplified the function call, go to myapp/application/config/autoload.php, then modify the $autoload['helper'] value:
$autoload['helper'] = array('url');
STEP 5 Modify Route Configuration
Open myapp/application/config/routes.php file, then modify $route['default_controller'] value. In this tutorial, i decide the Actor controller is my main default page.
$route['default_controller'] = 'Actor';
STEP 6 Create The Model
Every model should be placed at myapp/application/models directory. The main goal is to make user capable of doing CRUD operation on "actor" data. Create actor model with name m_actor that has four functions:
- listActor
Display all actor data. - insertActor
Insert a new actor data. - updateActor
Update an actor data. - removeActor
Remove an actor data.
The code of m_actor:
<?php
class M_actor extends CI_Model
{
function getAllActors()
{
$query = $this->db->get('actor');
return $query;
}
function getActor($actor_id)
{
$tablename = 'actor';
return $this->db->get_where($tablename, array('actor_id' => $actor_id))->row();
}
function insertActor($data)
{
$tablename = 'actor';
$status = $this->db->insert($tablename, $data);
return $status;
}
function updateActor($data, $actor_id)
{
$tablename = 'actor';
$this->db->where('actor_id', $actor_id);
$status = $this->db->update($tablename, $data);
return $status;
}
function removeActor($actor_id)
{
return $this->db->delete('actor', array('actor_id'=>$actor_id));
}
}
STEP 7 Create The View
Every view should be placed at myapp/application/views directory.
First, create container or layout where every page loaded. Below simple layout named as layout.php:
<!DOCTYPE html>
<html>
<head>
<title>Simple CRUD</title>
</head>
<body>
<?php $this->load->view($page);?>
</body>
</html>
Then, create new folder called actor, then create three new files:
- index.php
This view will display all actors data.
<a href="<?php echo base_url()."index.php/actor/create" ?>">Add New Actor</a> <table width="100%" border="0" cellspacing="1" cellpadding="5"> <tr class="rowheader"> <td width="4%" align="center">No</td> <td width="21%" align="center">Full Name</td> <td width="14%" align="center">Last Updated</td> <td width="19%" align="center"> </td> </tr> <?php $i=1; foreach($actors->result() as $row) { ?> <tr class="rowcontent"> <td><?php echo $i ?></td> <td><?php echo $row->fullname?></td> <td><?php echo $row->last_update ?></td> <td align="center"> <div class="rowmenu"> <a href="<?php echo base_url().'index.php/actor/read/'.$row->actor_id ?>">View</a> <a href="<?php echo base_url().'index.php/actor/edit/'.$row->actor_id ?>">Edit</a> <a href="<?php echo base_url().'index.php/actor/delete/'.$row->actor_id ?>">Delete</a> </div> </td> </tr> <?php $i++; } ?> </table>
- view.php
This view will display single actor data filtered by id.
<table width="100%" border="0" cellspacing="1" cellpadding="5"> <tr class="rowheader"> <td width="21%" align="center">Full Name</td> <td width="14%" align="center">Last Updated</td> </tr> <tr class="rowcontent"> <td><?php echo $actor->fullname?></td> <td><?php echo $actor->last_update ?></td> </tr> </table>
- form.php
This view will handle the create and update an actor data.
<?php $namaLengkap = ""; $id = ""; $title = "Buat Actor Baru"; $actionPath = "actor/create"; if (isset($actor->fullname) && isset($actor->actor_id)) { $namaLengkap = $actor->fullname; $id = $actor->actor_id; $title = "Edit Actor"; $actionPath = "actor/edit/$id"; } ?> <h3><?php echo $title ?></h3> <form action="<?php echo base_url().$actionPath ?>" method="post" enctype="multipart/form-data" name="actor_form"> <table width="100%" border="0" cellspacing="0" cellpadding="5"> <tr> <td width="23%" align="left">Full Name</td> <td width="1%">:</td> <td width="76%"> <input type="text" name="fullname" id="namajenis" placeholder="Full Name" required value="<?php echo $namaLengkap ?>"> </td> </tr> <tr> <td align="left" valign="top"> <input type="hidden" name="actor_id" id="id" value="<?php echo $id ?>"> </td> <td valign="top"> </td> <td> <input type="submit" name="button" id="button" value="Simpan"> <input type="reset" name="button2" id="button2" value="Reset" /> </td> </tr> </table> </form>
STEP 8 Create The Controller
Every view should be placed at myapp/application/controllers directory.
Our controller file named as Actor.php have five function:
Our controller file named as Actor.php have five function:
- Construct
Initialization condition should be occurred here. Our models, libraries, helpers, etc should be called here. - Index
Handle for displaying all actors data. - Create
Handle for creating new actor data. - ReadHandle for reading single actor data.
- Edit
Handle for updating new actor data. - Delete
Handle for deleting new actor data.
Below, compleate code of Actor.php:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Actor extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->model('m_actor');
}
public function index()
{
$data['page'] = 'actor/index';
$actors = $this->m_actor->getAllActors();
$data['actors'] = $actors;
$this->load->view('layout', $data);
}
public function create()
{
if ($this->input->server('REQUEST_METHOD') == 'GET') {
$data['page'] = 'actor/form';
$this->load->view('layout', $data);
} else if($this->input->server('REQUEST_METHOD') == 'POST') {
$data = array(
'fullname' => $this->input->post('fullname'),
'last_update' => date("Y-m-d H:i:s")
);
$status = $this->m_actor->insertActor($data);
if ($status)
{
$this->session->set_flashdata('info', '<div class="success">Actor created</div>');
redirect('actor');
}
}
}
public function read($actor_id)
{
$data['page'] = 'actor/view';
$actor = $this->m_actor->getActor($actor_id);
$data['actor'] = $actor;
$this->load->view('layout', $data);
}
public function edit($actor_id)
{
if ($this->input->server('REQUEST_METHOD') == 'GET') {
$data['page'] = 'actor/form';
$actor = $this->m_actor->getActor($actor_id);
$data['actor'] = $actor;
$this->load->view('layout', $data);
} else if($this->input->server('REQUEST_METHOD') == 'POST') {
$data = array(
'fullname' => $this->input->post('fullname'),
'last_update' => date("Y-m-d H:i:s")
);
$actor_id = $this->input->post('actor_id');
$status = $this->m_actor->updateActor($data, $actor_id);
if($status)
{
$this->session->set_flashdata('info','<div class="success">Actor updated</div>');
redirect('actor');
}
}
}
public function delete($actor_id)
{
$status = $this->m_actor->removeActor($actor_id);
if ($status) {
$this->session->set_flashdata('info', '<div class="success">Actor deleted</div>');
redirect('actor');
}
}
}
STEP 9 Try It !
Now, it's time to access http://localhost/ci-crud/index.php/actor
0 comments :
Post a Comment