CodeIgniter CRUD with Pagination

CodeIgniter Complete Crud with Paginations

After learning how to use a database then we will try to do the basic commands on information systems CRUD (CREATE, READ, UPDATE, and DELETE) data using CodeIgniter. Besides CRUD in this example will also do the sorting and pagination. Case studies will be raised is the student data form.

In this Article CRUD application to be created is an application that has a function to display all student data. Data shown have pagination (the distribution of the number of records displayed on a page website). Pagination is needed because we cannot possibly list all the data in a single layer.

Besides a list of students was to feature sorting by field and have a list of student action menu.

To do pagination in CodeIgniter Library classes which provide a pagination class? To use this class must have at least three further data will be set up in the library. Third is the pagination data base_url, total_row (the total number of rows or records that we had) and per_page (number of rows to be displayed per page example

 $this->load->library('pagination');

$this->load->helper('url');

$config['base_url']=site_url('results/page/');

$config['total_rows']=200;

$config['per_page']=20;

$this->pagination->initialize($config);

echo $this->pagination->create_links();
 

The above example shows how to use pagination library. The output of this library is composed of links of the page and a link to the next page (next)or previous (prev). Base_url should contain a function of the controller. The function will receive two parameters: the number of records and record per page what a show. In addition to the above parameters are still many other parameters that can be used to customize the pagination library.

As for a favorite author is


// put the record information on the uri to 3

$config['uri_segment'] = 3;

// change the writing next to Next>

$config['next_link'] = 'Next >';

// replace the prev posts to < previous

$config['prev_link'] = '&lt; previous';
 

The steps that must be done to make the CRUD and pagination is

1. Creating Student Database and Table Data

to get started, you need to have a database. In addition to the database, you must create a table of students. The table that must be made is


CREATE TABLE IF NOT EXISTS `student` (

`id` bigint(20) NOT NULL AUTO_INCREMENT,

`name` varchar(50) DEFAULT NULL,

`address` varchar(200) NOT NULL,

`gender` char(1) DEFAULT NULL,

`date_of_birth` date DEFAULT NULL,

PRIMARY KEY (`id`)

) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Insert Sample Data to your student table:


INSERT INTO `student` (`id`, `name`, `address`, `gender`, `date_of_birth`) VALUES

(1, 'Adnan', 'Dhanmondi, Shankar', 'M', '1990-12-03'),

(2, 'Tisha', 'khelgaon,Dhaka', 'F', '1962-12-31'),

(3, 'Khurshed', 'Zigatola, Dhaka', 'M', '2000-12-01'),

(4, 'Shopno baaz Ovi', 'Kumilla, Bangladesh', 'M', '2012-12-05'),

(5, 'Tora', 'mali baag', 'F', '1944-12-26'),

(6, 'Sadman', 'Mohakhali,Bangladesh', 'F', '1989-12-31'),

(7, 'Rabu', 'khilgaon', 'M', '1987-12-03'),

(8, 'Mahfuz', 'Mirpur,Dhaka', 'M', '1992-12-17'),

(9, 'Hazera Akter', 'Shankar,Dhaka', 'F', '1988-12-09'),

(10, 'Al-Amin', 'Gopalgonj,Bangladesh', 'M', '1989-12-14'),

(11, 'Yakub Mizan', 'Ctg, Bangladesh', 'M', '1990-12-04'),

(12, 'Mamun Haque', 'Dhaka,Bangladesh', 'F', '1993-12-10');

The table has five students in the field that the student id, student name, student address, gender, and date of birth. This table is used for storing student data.

2. Configuring CodeIgniter

Before you start coding, we need to configure the tools to be used. There are three configurations to be adjusted, such as: config.php, database.php and router.php. As for who should do is:

$config.php:

in configuration file that needs to be changed is the base_url. configuration serves to determine the base path of the application. This configuration will used by the form and the url helper. Examples of changes made:

$database.php:

configuration doing here so that the application can connect to the database.

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

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

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

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

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

$router.php:

contains the default configuration and routing controller rule. In this configuration the default controller changed only

 $route['default_controller'] = "student";
 

1. Make Model Student

The model is a model student in charge and responsible for the processes associated with the database. For example, store, modify, delete and retrieve data from the database.

Usually to help us, following the modeling or database design can mean one table can be represented by a single model. The model is exactly what is
responsible for all operations on the table.

In this CRUD application we will create a model student. The content of the student models are:

 <?php

class Student_model extends CI_Model{

private $primary_key='id';

private $table_name='student';

function __consturct(){

parent::__construct();

}

function get_paged_list($limit=10, $offset=0, $order_column='', $order_type='asc'){

if(empty($order_column)||empty($order_type)){

$this->db->order_by($this->primary_key,'asc');

}

else{

$this->db->order_by($order_column,$order_type);

return $this->db->get($this->table_name, $limit, $offset);

}

}

function count_all(){

return $this->db->count_all($this->table_name);

}

function get_by_id($id){

$this->db->where($this->primary_key,$id);

return $this->db->get($this->table_name);

}

function save($person){

$this->db->insert($this->table_name,$person);

return $this->db->insert_id();

}

function update($id,$person){

$this->db->where($this->primary_key,$id);

$this->db->update($this->table_name,$person);

}

function delete($id){

$this->db->where($this->primary_key,$id);

$this->db->delete($this->table_name);

}

}

?>

 

$ config ['base_rul'] = 'http://localhost/crud', / / replace as your path in server

1. Make Controller and View Student Data

Controller contains the logic to make the existing processes. As for the process to be handled by the controller is to display a list of students, increase student, change the student data, delete the student data and see detail students.


<?php

class Student extends CI_Controller {

private $limit = 5;

function __construct()

{

parent::__construct();

#load library dan helper yang dibutuhkan

$this->load->library(array('table','form_validation'));

$this->load->helper(array('form', 'url'));

$this->load->model('Student_model','',TRUE);

}

function index($offset = 0, $order_column = 'id', $order_type = 'asc')

{

if (empty($offset)) $offset = 0;

if (empty($order_column)) $order_column = 'id';

if (empty($order_type)) $order_type = 'asc';

//TODO: check for valid column

// load data

$Students = $this->Student_model->get_paged_list($this->limit, $offset, $order_column, $order_type)->result();

// generate pagination

$this->load->library('pagination');

$config['base_url'] = site_url('Student/index/');

$config['total_rows'] = $this->Student_model->count_all();

$config['per_page'] = $this->limit;

$config['uri_segment'] = 3;

$this->pagination->initialize($config);

$data['pagination'] = $this->pagination->create_links();

// generate table data

$this->load->library('table');

$this->table->set_empty("");

$new_order = ($order_type == 'asc' ? 'desc' : 'asc');

$this->table->set_heading(

'No',

anchor('Student/index/'.$offset.'/name/'.$new_order, 'Name'),

anchor('Student/index/'.$offset.'/address/'.$new_order, 'Address'),

anchor('Student/index/'.$offset.'/gender/'.$new_order, 'Gender'),

anchor('Student/index/'.$offset.'/date_of_birth/'.$new_order, 'Date Of Birth (dd-mm-yyyy)'),

'Actions'

);

$i = 0 + $offset;

foreach ($Students as $Student){

$this->table->add_row(++$i,

$Student->name,

$Student->address,

strtoupper($Student->gender)=='M'? '

Male':'Women',

date('d-m-Y',strtotime($Student->date_of_birth)),

anchor('Student/view/'.$Student->id,'view',array('class'=>'view')).' '.

anchor('Student/update/'.$Student->id,'update',array('class'=>'update')).' '.

anchor('Student/delete/'.$Student->id,'delete',array('class'=>'delete','onclick'=>"return confirm('Are you sure you want to remove this Student?')"))

);

}

$data['table'] = $this->table->generate();

if ($this->uri->segment(3)=='delete_success')

$data['message'] = 'The Data was successfully deleted';

else if ($this->uri->segment(3)=='add_success')

$data['message'] = 'The Data has been successfully added';

else

$data['message'] = '';

// load view

$this->load->view('StudentList', $data);

}

function add(){

// set common properties

$data['title'] = 'Add New Student';

$data['action'] = site_url('Student/add');

$data['link_back'] = anchor('Student/index/','Back to list of Students',array('class'=>'back'));

$this->_set_rules();

// run validation

if ($this->form_validation->run() === FALSE){

$data['message'] = '';

// set common properties

$data['title'] = 'Add new Student';

$data['message'] = '';

$data['Student']['id']='';

$data['Student']['name']='';

$data['Student']['address']='';

$data['Student']['gender']='';

$data['Student']['date_of_birth']='';

$data['link_back'] = anchor('Student/index/','See List Of Student',array('class'=>'back'));

$this->load->view('StudentEdit', $data);

}else{

// save data

$Student = array('name' => $this->input->post('name'),

'address' => $this->input->post('address'),

'gender' => $this->input->post('gender'),

'date_of_birth' => date('Y-m-d', strtotime($this->input->post('date_of_birth'))));

$id = $this->Student_model->save($Student);

// set form input name="id"

$this->validation->id = $id;

redirect('Student/index/add_success');

}

}

function view($id){

// set common properties

$data['title'] = 'Student Details';

$data['link_back'] = anchor('Student/index/','List Of Student',array('class'=>'back'));

// get Student details

$data['Student'] = $this->Student_model->get_by_id($id)->row();

// load view

$this->load->view('StudentView', $data);

}

function update($id){

// set common properties

$data['title'] = 'Update Student';

$this->load->library('form_validation');

// set validation properties

$this->_set_rules();

$data['action'] = ('Student/update/'.$id);

// run validation

if ($this->form_validation->run() === FALSE){

$data['message'] = '';

$data['Student'] = (array)$this->Student_model->get_by_id($id)->row();

$_POST['gender'] = strtoupper($data['Student']['gender']);

$data['Student']['date_of_birth'] = date('d-m-Y',strtotime($data['Student']['date_of_birth']));

// set common properties

$data['title'] = 'Update Student';

$data['message'] = '';

}else{

// save data

$id = $this->input->post('id');

$Student = array('name' => $this->input->post('name'),

'address' => $this->input->post('address'),

'gender' => $this->input->post('gender'),

'date_of_birth' => date('Y-m-d', strtotime($this->input->post('date_of_birth'))));

var_dump($Student);

$this->Student_model->update($id,$Student);

$data['Student'] = (array)$this->Student_model->get_by_id($id)->row();

// set user message

$data['message'] = 'update Student success';

}

$data['link_back'] = anchor('Student/index/','List Of Student',array('class'=>'back'));

// load view

$this->load->view('StudentEdit', $data);

}

function delete($id){

// delete Student

$this->Student_model->delete($id);

// redirect to Student list page

redirect('Student/index/delete_success','refresh');

}

// validation rules

function _set_rules(){

$this->form_validation->set_rules('name', 'Name', 'required|trim');

$this->form_validation->set_rules('gender', 'Password', 'required');

$this->form_validation->set_rules('address', 'Address', 'required|callback_valid_date');

$this->form_validation->set_rules('date_of_birth', 'Date Of Birth', 'required');

}

// date_validation callback

function valid_date($str)

{

if(!preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/', $str))

{

$this->form_validation->set_message('valid_date', 'date format is not valid. yyyy-mm-dd');

return false;

}

else

{

return true;

}

}

}

?>

Note the lines in the function index ($offset = 0, $order_colmn = ‘ id ‘, $order_type = ‘ asc ‘). On the function There are three optional parameters that can be given through a URI. The parameter $ offset function to determine the first record to be displayed, $order_column function to determine what field you want to use to sort the data students and $ order_type function to determine the sort order (ascending or descending). To get the data according to the requirements (sorting and pagination) then called get_paged_list (line 37). After the student data obtained will be used to display table data libraries in the form of a table such as the look  in (lines 61-105).

Display Student Lists:

To get the display Lists, you need to be made a view like this.

This View is stored in a file named studentList.php


<!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>

<h1>Example Insert Update and delete</h1>

<div class="paging"><?php echo $pagination; ?></div>

<div class="data"><?php echo $table; ?></div>

<div class="paging"><?php echo $pagination; ?></div>

<br />

<?php echo anchor('Student/add/','Add new students',array('class'=>'add')); ?>

</div>

</body>

</html>

And Finally Create crud/style.css file in your project root folder

 body {

background-color: #fff;

margin: 0px;

font-family: Lucida Grande, Verdana, Sans-serif;

font-size: 8px;

color: #4F5155;

}

a {

color: #003399;

background-color: transparent;

font-weight: normal;

}

h1 {

color: #444;

background-color: transparent;

border-bottom: 1px solid #D0D0D0;

font-size: 8px;

font-weight: bold;

margin: 0px 0 2px 0;

padding: 5px 0 6px 0;

}

div.content {

padding:2px 5px;

}

div.content div.data table {

border:2px solid #000;

background:#fff;

width:60%;

}

div.content div.data table td {

font-size:8pt;

padding:5px 5px;

border-bottom:1px solid #ddd;

text-align: left;

}

div.paging {

font-size: 7pt;

margin:5px 0px;

width:60%;

text-align:right;

}

div.paging a {

color:#900;

text-transform: uppercase;

text-decoration: none;

}

div.paging a:hover {

color:#c00;

}

div.paging b {

color:#900;

}

Now, test your application. Point your browser to http://localhost/crud You should get like this

Display Data Using CodeIgniter Crud

Edit/Update Students:

In addition to displaying data, the controller above has a function to change data and add the students. Both functions are essentially the same. The difference is the action or the model function is called and calling of the record that you want to edit. Note the add function on line 125. On the add function is exercised against the calling function $this-> _ set_rules (); the function is used to set the validation rule. If the input entered by the user in accordance with the validation rule will be called functions $this-> Student_model-> save to save the data. As for the view that is used is

View/studentEdit.php


<!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>

<?php echo $message; ?>

<?php echo validation_errors(); ?>

<?php echo form_open($action); ?>

<div class="data">

<table>

<tr>

<td width="30%">ID</td>

<td><input type="text" name="id" disabled="disable" class="text" value="<?php echo (isset($Student['id']))?$Student['id']:''; ?>"/></td>

<input type="hidden" name="id" value="<?php echo (isset($Student['id']))?$Student['id']:''; ?>"/>

</tr>

<tr>

<td valign="top">name<span style="color:red;">*</span></td>

<td><input type="text" name="name" value="<?php echo (set_value('name'))?set_value('name'):$Student['name']; ?>"/>

<?php echo form_error('name'); ?></td>

</tr>

<tr>

<td valign="top">Address</td>

<td><input type="text" name="address" value="<?php echo set_value('address')?set_value('address'):$Student['address']; ?>"/>

<?php echo form_error('address'); ?></td>

</tr>

<tr>

<td valign="top">Gender<span style="color:red;">*</span></td>

<td><input type="radio" name="gender" value="M" <?php echo set_radio('gender', 'M', TRUE); ?>/> Male

<input type="radio" name="gender" value="F" <?php echo set_radio('gender', 'F'); ?>/> Female

<?php echo form_error('gender'); ?></td>

</tr>

<tr>

<td valign="top">Date of birth (dd-mm-yyyy)<span style="color:red;">*</span></td>

<td><input type="text" name="date_of_birth" value="<?php echo (set_value('date_of_birth'))?set_value('date_of_birth'):$Student['date_of_birth']; ?>"/>

<?php echo form_error('date_of_birth'); ?></td>

</tr>

<tr>

<td></td>

<td><input type="submit" value="Save"/></td>

</tr>

</table>

</div>

</form>

<br />

<?php echo $link_back; ?>

</div>

</body>

</html>

View on the edit function is also used by students. Storage it is necessary to perform a function called $this-> Student_model-> update ($id, $students); on the function needs to include the student id and student data that has been updated.

Update Data Using CodeIgniter CRUD

In addition to the add and change, there are also functions for delete and view details of the students. To remove a student id is only required of students who want to delete. As for seeing detail data students things to do is to call the student data based on the student id is then displayed to the

in view of the following:

view/studentView.php


<!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 $Student->id; ?></td>

</tr>

<tr>

<td valign="top">Name Student</td>

<td><?php echo $Student->name; ?></td>

</tr>

<tr>

<td valign="top">Address</td>

<td><?php echo $Student->address; ?></td>

</tr>

<tr>

<td valign="top">Gender</td>

<td><?php echo strtoupper($Student->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($Student->date_of_birth)); ?></td>

</tr>

</table>

</div>

<br />

<?php echo $link_back; ?>

</div>

</body>

</html>

Display Details Data using CodeIgniter CRUD

Before performing delete confirmation needs to be done to prevent user errors in pressing the link  action.

Delete Data with CodeIgnite Crud

Happy CodeIgniter :)

This entry was posted in CODEIGNITER and tagged by Masud Alam. Bookmark the permalink.

About Masud Alam

Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka, Bangladesh. I graduated in 2009 with a bachelor's degree in Computer Science and Engineering from State University Of Bangladesh, I'm also a Certified Engineer on ZEND PHP 5.3, I served my first three years as a software Engineer at a software firm, but now i'm a founder & CEO of TechBeeo Software Ltd. and Course Instructor of ZCE PHP 5.3 Certification and professional web development course at Country Leading Training Institute IBCS-PRIMAX Software (Bangladesh) Ltd.

9 thoughts on “CodeIgniter CRUD with Pagination

  1. hi! Masud alam! i am new to codeigniter..i have tried your code…its working fine..but when i try to implement a calender script to select date of birth..on submit it shows..date format not valid….can u help me out…plz….Thank u in advance

  2. Thanks for those extremely helpful tutorials bhaya.
    An opinion as of being a keen reader of your blog:
    Your articles are little lengthy.
    If you could cut it in pieces that’d help new comers.

    Thanks again.

    • Hi,
      I am pradip, from kolkata this tutorial section is really very very helpful and i want to connented asa developer as you.
      Thanls

  3. Hi,
    I am pradip, from kolkata this tutorial section is really very very helpful and i want to connented asa developer as you.
    Thanls

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>