Henri Blog

Study and Share knowledge

Simple CRUD – CodeIgniter

with 20 comments

A couple months ago i have developed PHP application. That’s was the first time (and the only one) i used CodeIgniter. The development itself only took a short period, thanks to helpful plugins and libraries such as excel_reader, jpgraph, dompdf and many more. At this moment, i want to share my humble knowledge in creating simple PHP application.

As the title suggest, we are going to create simple CRUD (Create Read Update Delete) application using CodeIgniter framework. The application that we are going to build is not a complex application (that’s why we call it “simple”) but consists of features such as pagination and simple validation.

Here, i’m using CodeIgniter_1.6.3 and MySql 5. Let’s begin.

  1. Database schema. run this script.
    CREATE DATABASE crud;
    
    USE crud;
    CREATE TABLE tbl_person
    (
      id bigint auto_increment PRIMARY KEY,
      name varchar(50),
      gender char(1),
      dob date
    );
    
    INSERT tbl_person (name,gender,dob) VALUES('henrihnr', 'm', '1985-09-09');
    INSERT tbl_person (name,gender,dob) VALUES('name_001', 'm', '1990-01-01');
    INSERT tbl_person (name,gender,dob) VALUES('name_002', 'f', '2000-01-01');
    INSERT tbl_person (name,gender,dob) VALUES('name_003', 'm', '2000-02-02');
    INSERT tbl_person (name,gender,dob) VALUES('name_005', 'f', '2000-04-04');
  2. Database configuration. file: CodeIgniter\system\application\config\database.php
    $active_group = "default";
    $active_record = TRUE;
    
    $db['default']['hostname'] = "localhost";
    $db['default']['username'] = "root";
    $db['default']['password'] = "";
    $db['default']['database'] = "crud";
    $db['default']['dbdriver'] = "mysql";
  3. Base url configuration. file: CodeIgniter\system\application\config\config.php
    $config['base_url']	= "http://127.0.0.1/CodeIgniter/";
  4. Default controller configuration. file: CodeIgniter\system\application\config\routes.php
    $route['default_controller'] = "person";
  5. Model. create file CodeIgniter\system\application\models\personModel.php. Here we are using active record class.
    class PersonModel extends Model {
    	// table name
    	private $tbl_person= 'tbl_person';
    
    	function Person(){
    		parent::Model();
    	}
    	// get number of persons in database
    	function count_all(){
    		return $this->db->count_all($this->tbl_person);
    	}
    	// get persons with paging
    	function get_paged_list($limit = 10, $offset = 0){
    		$this->db->order_by('id','asc');
    		return $this->db->get($this->tbl_person, $limit, $offset);
    	}
    	// get person by id
    	function get_by_id($id){
    		$this->db->where('id', $id);
    		return $this->db->get($this->tbl_person);
    	}
    	// add new person
    	function save($person){
    		$this->db->insert($this->tbl_person, $person);
    		return $this->db->insert_id();
    	}
    	// update person by id
    	function update($id, $person){
    		$this->db->where('id', $id);
    		$this->db->update($this->tbl_person, $person);
    	}
    	// delete person by id
    	function delete($id){
    		$this->db->where('id', $id);
    		$this->db->delete($this->tbl_person);
    	}
    }
  6. Controller. create file CodeIgniter\system\application\controllers\person.php
    <?php
    class Person extends Controller {
    
    	// num of records per page
    	private $limit = 10;
    
    	function Person(){
    		parent::Controller();
    
    		// load library
    		$this->load->library(array('table','validation'));
    
    		// load helper
    		$this->load->helper('url');
    
    		// load model
    		$this->load->model('personModel','',TRUE);
    	}
    
    	function index($offset = 0){
    		// offset
    		$uri_segment = 3;
    		$offset = $this->uri->segment($uri_segment);
    
    		// load data
    		$persons = $this->personModel->get_paged_list($this->limit, $offset)->result();
    
    		// generate pagination
    		$this->load->library('pagination');
    		$config['base_url'] = site_url('person/index/');
     		$config['total_rows'] = $this->personModel->count_all();
     		$config['per_page'] = $this->limit;
    		$config['uri_segment'] = $uri_segment;
    		$this->pagination->initialize($config);
    		$data['pagination'] = $this->pagination->create_links();
    
    		// generate table data
    		$this->load->library('table');
    		$this->table->set_empty("&nbsp;");
    		$this->table->set_heading('No', 'Name', 'Gender', 'Date of Birth (dd-mm-yyyy)', 'Actions');
    		$i = 0 + $offset;
    		foreach ($persons as $person){
    			$this->table->add_row(++$i, $person->name, strtoupper($person->gender)=='M'? 'Male':'Female', date('d-m-Y',strtotime($person->dob)),
    				anchor('person/view/'.$person->id,'view',array('class'=>'view')).' '.
    				anchor('person/update/'.$person->id,'update',array('class'=>'update')).' '.
    				anchor('person/delete/'.$person->id,'delete',array('class'=>'delete','onclick'=>"return confirm('Are you sure want to delete this person?')"))
    			);
    		}
    		$data['table'] = $this->table->generate();
    
    		// load view
    		$this->load->view('personList', $data);
    	}
    
    	function add(){
    		// set validation properties
    		$this->_set_fields();
    
    		// set common properties
    		$data['title'] = 'Add new person';
    		$data['message'] = '';
    		$data['action'] = site_url('person/addPerson');
    		$data['link_back'] = anchor('person/index/','Back to list of persons',array('class'=>'back'));
    
    		// load view
    		$this->load->view('personEdit', $data);
    	}
    
    	function addPerson(){
    		// set common properties
    		$data['title'] = 'Add new person';
    		$data['action'] = site_url('person/addPerson');
    		$data['link_back'] = anchor('person/index/','Back to list of persons',array('class'=>'back'));
    
    		// set validation properties
    		$this->_set_fields();
    		$this->_set_rules();
    
    		// run validation
    		if ($this->validation->run() == FALSE){
    			$data['message'] = '';
    		}else{
    			// save data
    			$person = array('name' => $this->input->post('name'),
    							'gender' => $this->input->post('gender'),
    							'dob' => date('Y-m-d', strtotime($this->input->post('dob'))));
    			$id = $this->personModel->save($person);
    
    			// set form input name="id"
    			$this->validation->id = $id;
    
    			// set user message
    			$data['message'] = '<div class="success">add new person success</div>';
    		}
    
    		// load view
    		$this->load->view('personEdit', $data);
    	}
    
    	function view($id){
    		// set common properties
    		$data['title'] = 'Person Details';
    		$data['link_back'] = anchor('person/index/','Back to list of persons',array('class'=>'back'));
    
    		// get person details
    		$data['person'] = $this->personModel->get_by_id($id)->row();
    
    		// load view
    		$this->load->view('personView', $data);
    	}
    
    	function update($id){
    		// set validation properties
    		$this->_set_fields();
    
    		// prefill form values
    		$person = $this->personModel->get_by_id($id)->row();
    		$this->validation->id = $id;
    		$this->validation->name = $person->name;
    		$_POST['gender'] = strtoupper($person->gender);
    		$this->validation->dob = date('d-m-Y',strtotime($person->dob));
    
    		// set common properties
    		$data['title'] = 'Update person';
    		$data['message'] = '';
    		$data['action'] = site_url('person/updatePerson');
    		$data['link_back'] = anchor('person/index/','Back to list of persons',array('class'=>'back'));
    
    		// load view
    		$this->load->view('personEdit', $data);
    	}
    
    	function updatePerson(){
    		// set common properties
    		$data['title'] = 'Update person';
    		$data['action'] = site_url('person/updatePerson');
    		$data['link_back'] = anchor('person/index/','Back to list of persons',array('class'=>'back'));
    
    		// set validation properties
    		$this->_set_fields();
    		$this->_set_rules();
    
    		// run validation
    		if ($this->validation->run() == FALSE){
    			$data['message'] = '';
    		}else{
    			// save data
    			$id = $this->input->post('id');
    			$person = array('name' => $this->input->post('name'),
    							'gender' => $this->input->post('gender'),
    							'dob' => date('Y-m-d', strtotime($this->input->post('dob'))));
    			$this->personModel->update($id,$person);
    
    			// set user message
    			$data['message'] = '<div class="success">update person success</div>';
    		}
    
    		// load view
    		$this->load->view('personEdit', $data);
    	}
    
    	function delete($id){
    		// delete person
    		$this->personModel->delete($id);
    
    		// redirect to person list page
    		redirect('person/index/','refresh');
    	}
    
    	// validation fields
    	function _set_fields(){
    		$fields['id'] = 'id';
    		$fields['name'] = 'name';
    		$fields['gender'] = 'gender';
    		$fields['dob'] = 'dob';
    
    		$this->validation->set_fields($fields);
    	}
    
    	// validation rules
    	function _set_rules(){
    		$rules['name'] = 'trim|required';
    		$rules['gender'] = 'trim|required';
    		$rules['dob'] = 'trim|required|callback_valid_date';
    
    		$this->validation->set_rules($rules);
    
    		$this->validation->set_message('required', '* required');
    		$this->validation->set_message('isset', '* required');
    		$this->validation->set_error_delimiters('<p class="error">', '</p>');
    	}
    
    	// date_validation callback
    	function valid_date($str)
    	{
    		if(!ereg("^(0[1-9]|1[0-9]|2[0-9]|3[01])-(0[1-9]|1[012])-([0-9]{4})$", $str))
    		{
    			$this->validation->set_message('valid_date', 'date format is not valid. dd-mm-yyyy');
    			return false;
    		}
    		else
    		{
    			return true;
    		}
    	}
    }
    ?>
  7. View. create 3 files at CodeIgniter\system\application\views folder. personList.php to list persons with pagination
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    
    <title>SIMPLE CRUD APPLICATION</title>
    
    <link href="<?php echo base_url(); ?>style/style.css" rel="stylesheet" type="text/css" />
    
    </head>
    <body>
    	<div class="content">
    		<h1>Simple CRUD Application</h1>
    		<div class="paging"><?php echo $pagination; ?></div>
    		<div class="data"><?php echo $table; ?></div>
    		<br />
    		<?php echo anchor('person/add/','add new data',array('class'=>'add')); ?>
    	</div>
    </body>
    </html>

    personEdit.php to add or update a person

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    
    <title>SIMPLE CRUD APPLICATION</title>
    
    <link href="<?php echo base_url(); ?>style/style.css" rel="stylesheet" type="text/css" />
    
    <link href="<?php echo base_url(); ?>style/calendar.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="<?php echo base_url(); ?>script/calendar.js"></script>
    
    </head>
    <body>
    	<div class="content">
    		<h1><?php echo $title; ?></h1>
    		<?php echo $message; ?>
    		<form method="post" action="<?php echo $action; ?>">
    		<div class="data">
    		<table>
    			<tr>
    				<td width="30%">ID</td>
    				<td><input type="text" name="id" disabled="disable" class="text" value="<?php echo $this->validation->id; ?>"/></td>
    				<input type="hidden" name="id" value="<?php echo $this->validation->id; ?>"/>
    			</tr>
    			<tr>
    				<td valign="top">Name<span style="color:red;">*</span></td>
    				<td><input type="text" name="name" class="text" value="<?php echo $this->validation->name; ?>"/>
    				<?php echo $this->validation->name_error; ?></td>
    			</tr>
    			<tr>
    				<td valign="top">Gender<span style="color:red;">*</span></td>
    				<td><input type="radio" name="gender" value="M" <?php echo $this->validation->set_radio('gender', 'M'); ?>/> M
    					<input type="radio" name="gender" value="F" <?php echo $this->validation->set_radio('gender', 'F'); ?>/> F
    					<?php echo $this->validation->gender_error; ?></td>
    			</tr>
    			<tr>
    				<td valign="top">Date of birth (dd-mm-yyyy)<span style="color:red;">*</span></td>
    				<td><input type="text" name="dob" onclick="displayDatePicker('dob');" class="text" value="<?php echo $this->validation->dob; ?>"/>
    				<a href="javascript:void(0);" onclick="displayDatePicker('dob');"><img src="<?php echo base_url(); ?>style/images/calendar.png" alt="calendar" border="0"></a>
    				<?php echo $this->validation->dob_error; ?></td>
    			</tr>
    			<tr>
    				<td>&nbsp;</td>
    				<td><input type="submit" value="Save"/></td>
    			</tr>
    		</table>
    		</div>
    		</form>
    		<br />
    		<?php echo $link_back; ?>
    	</div>
    </body>
    </html>

    personView.php to view a person details

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    
    <title>SIMPLE CRUD APPLICATION</title>
    
    <link href="<?php echo base_url(); ?>style/style.css" rel="stylesheet" type="text/css" />
    
    </head>
    <body>
    	<div class="content">
    		<h1><?php echo $title; ?></h1>
    		<div class="data">
    		<table>
    			<tr>
    				<td width="30%">ID</td>
    				<td><?php echo $person->id; ?></td>
    			</tr>
    			<tr>
    				<td valign="top">Name</td>
    				<td><?php echo $person->name; ?></td>
    			</tr>
    			<tr>
    				<td valign="top">Gender</td>
    				<td><?php echo strtoupper($person->gender)=='M'? 'Male':'Female' ; ?></td>
    			</tr>
    			<tr>
    				<td valign="top">Date of birth (dd-mm-yyyy)</td>
    				<td><?php echo date('d-m-Y',strtotime($person->dob)); ?></td>
    			</tr>
    		</table>
    		</div>
    		<br />
    		<?php echo $link_back; ?>
    	</div>
    </body>
    </html>
  8. Style. put stylesheet at CodeIgniter\style\style.css and style’s images at CodeIgniter\style\images folder

    body {
    	font-family:tahoma;
    	padding:0px;
    	margin:0px;
    	background:#f5f5f5
    }
    
    div.content {
    	padding:10px 20px;
    }
    div.content h1 {
    	font-size:18pt;
    	border-bottom:5px solid #a00;
    	padding:0px;
    	margin:10px 0px 20px;
    	width:80%;
    }
    
    div.content div.data table {
    	border:2px solid #000;
    	background:#fff;
    	width:80%;
    }
    div.content div.data table td {
    	font-size:10pt;
    	padding:5px 10px;
    	border-bottom:1px solid #ddd;
    	text-align: left;
    }
    div.content div.data table th {
    	text-align: left;
    	font-size: 8pt;
    	padding: 10px 10px 7px;
    	text-transform: uppercase;
    	color: #fff;
    	background:url(images/head.gif) left -5px repeat-x;
    }
    
    div.paging {
    	font-size: 9pt;
    	margin:5px 0px;
    }
    div.paging a {
    	color:#900;
    	text-transform: uppercase;
    	text-decoration: none;
    }
    div.paging a:hover {
    	color:#c00;
    }
    div.paging b {
    	color:#900;
    }
    
    div.success {
    	font-size:14pt;
    	background:url(images/accept.png) left 5px no-repeat;
    	padding:0px;
    	padding-left:20px;
    	margin:0px 0px 10px;
    	color:#060;
    	width:80%;
    }
    
    a.update, a.delete, a.add, a.view, a.back {
    	font-size: 9pt;
    	color:#900;
    	font-wight:bold;
    	padding-left:20px;
    	text-decoration: none;
    }
    a.update {
    	background:url(images/update.png) left center no-repeat;
    }
    a.delete {
    	background:url(images/delete.png) left center no-repeat;
    }
    a.add {
    	background:url(images/add.png) left center no-repeat;
    }
    a.view {
    	background:url(images/view.png) left center no-repeat;
    }
    a.back {
    	background:url(images/prev.gif) left center no-repeat;
    }
    a.update:hover, a.delete:hover, a.add:hover, a.view:hover {
    	color:#000;
    }
    
    input.text {
    	border:2px solid #aaa;
    }
    
    .error {
    	background: #FBE6F2 none repeat scroll 0 0;
    	border: 1px solid #D893A1;
    	color: #333333;
    	margin: 5px 0 0;
    	padding: 5px;
    	font-size: 10px;
    	font-family: Lucida Grande,Verdana,Geneva,Sans-serif;
    }
  9. Script. put script at CodeIgniter\script folder
  10. Done. Lets preview what should we have by now.
list_of_person

List of persons with pagination

add_new_person

Add new person

update_person

Update person

view_person

View person details

error_validation

Error on validation

Download Simple CRUD Application. Happy Programming!!

Written by Henri H.

April 26, 2009 at 12:21 am

Posted in PHP

Tagged with

20 Responses

Subscribe to comments with RSS.

  1. Hen … pala gua nyut2an ngeliatnya xD

    lunniey

    April 26, 2009 at 9:35 pm

  2. This is hot. This is exactly what I was looking for. Thanks!

    Aalaap Ghag

    May 8, 2009 at 8:47 pm

  3. hoho…great and good job my bro…
    i will try it…!!

    Santen

    May 24, 2009 at 11:10 am

  4. Thanks Bro, You save my life :)
    Good Job

    awan pribadi

    May 25, 2009 at 1:12 pm

  5. great tutorial great job, if the admin panel is also integrates then it’s a miracleous job
    thanks

    netvision

    May 30, 2009 at 4:54 pm

  6. Nice tutorial, when i started with codeigniter this is the tutorial that really helped me in expediting the project great job

    dharendera

    May 30, 2009 at 5:06 pm

  7. Thank You, God Bless You.
    Excellent Job.

    Alex Inoa

    July 16, 2009 at 4:59 am

  8. Thank you! [This should really be in the CI documentation.]

    q

    July 27, 2009 at 8:13 am

  9. Awesome brother, super cool

    Anuradha

    August 13, 2009 at 12:31 am

  10. I just posted on my blog a simple CRUD example with pagination and validation using CodeIgniter 1.7.1.
    My example uses this one as base, which I consider a very good example for those who are starting.

    Robertson Freitas

    August 24, 2009 at 12:39 pm

  11. thax a lot man.I got exactly whr i want.

    kabir

    August 27, 2009 at 1:50 pm

  12. Great Job!

    Just the article i needed to read to understand CI a little bit more. I just have a probleme with the redirect in the delete-function. Just see an empty page (maybe header already sent?). Wouldn’t $this->index() do the same?

    Many thanks
    Dirk

    Dirk

    August 29, 2009 at 12:27 am

  13. Mantap nich! Udah mendukung CRUD. Saya suka. Trim’s

    Nonpyrogenic

    September 11, 2009 at 10:03 pm

  14. [...] (que está mais para um Active Record Layer), incrivelmente reusável, foi inspirado no copiado do exemplo de CRUD que mencionei acima. Controller gordo + Model magro é considerado um anti-pattern, mas eu gosto [...]

  15. Thanks a lot. I was searching internet for a crud in ci. And this one serve my purpose very well. Thanks again.

    Azraf

    September 22, 2009 at 11:05 am

  16. wah..keren gw lagi perlu banget nih,,

    thank you very much..

    Tio

    October 2, 2009 at 10:41 am

  17. What a beautiful piece of work this is: useful, beautifully presented, and a fabulous base for anyone to build on, especially since you went beyond the usual text examples and included things like radio buttons and dates. Really really nice — thank you, Henri.

    Helen

    October 3, 2009 at 9:04 pm

  18. outstanding!!!!!!

    acatejr

    October 25, 2009 at 5:17 am

  19. This is awesome! Easily the best getting started tutorial on CodeIgniter. Thanks!

    Bill

    October 28, 2009 at 10:48 am

  20. Very nice job, very clean code, view is even better than on official examples.
    All the best!

    Frank

    November 6, 2009 at 5:20 am


Leave a Reply