Archive for the ‘Cakephp’ Category


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.
    01 CREATE DATABASE crud;
    02
    03 USE crud;
    04 CREATE TABLE tbl_person
    05 (
    06   id bigint auto_increment PRIMARY KEY,
    07   name varchar(50),
    08   gender char(1),
    09   dob date
    10 );
    11
    12 INSERT tbl_person (name,gender,dob) VALUES('henrihnr', 'm', '1985-09-09');
    13 INSERT tbl_person (name,gender,dob) VALUES('name_001', 'm', '1990-01-01');
    14 INSERT tbl_person (name,gender,dob) VALUES('name_002', 'f', '2000-01-01');
    15 INSERT tbl_person (name,gender,dob) VALUES('name_003', 'm', '2000-02-02');
    16 INSERT tbl_person (name,gender,dob) VALUES('name_005', 'f', '2000-04-04');
  2. Database configuration. file: CodeIgniter\system\application\config\database.php
    1 $active_group = "default";
    2 $active_record = TRUE;
    3
    4 $db['default']['hostname'] = "localhost";
    5 $db['default']['username'] = "root";
    6 $db['default']['password'] = "";
    7 $db['default']['database'] = "crud";
    8 $db['default']['dbdriver'] = "mysql";
  3. Base url configuration. file: CodeIgniter\system\application\config\config.php
    1 $config['base_url'] = "http://127.0.0.1/CodeIgniter/";
  4. Default controller configuration. file: CodeIgniter\system\application\config\routes.php
    1 $route['default_controller'] = "person";
  5. Model. create file CodeIgniter\system\application\models\personModel.php. Here we are using active record class.
    01 class PersonModel extends Model {
    02     // table name
    03     private $tbl_person= 'tbl_person';
    04
    05     function Person(){
    06         parent::Model();
    07     }
    08     // get number of persons in database
    09     function count_all(){
    10         return $this->db->count_all($this->tbl_person);
    11     }
    12     // get persons with paging
    13     function get_paged_list($limit = 10, $offset = 0){
    14         $this->db->order_by('id','asc');
    15         return $this->db->get($this->tbl_person, $limit, $offset);
    16     }
    17     // get person by id
    18     function get_by_id($id){
    19         $this->db->where('id', $id);
    20         return $this->db->get($this->tbl_person);
    21     }
    22     // add new person
    23     function save($person){
    24         $this->db->insert($this->tbl_person, $person);
    25         return $this->db->insert_id();
    26     }
    27     // update person by id
    28     function update($id, $person){
    29         $this->db->where('id', $id);
    30         $this->db->update($this->tbl_person, $person);
    31     }
    32     // delete person by id
    33     function delete($id){
    34         $this->db->where('id', $id);
    35         $this->db->delete($this->tbl_person);
    36     }
    37 }
  6. Controller. create file CodeIgniter\system\application\controllers\person.php
    001 <?php
    002 class Person extends Controller {
    003
    004     // num of records per page
    005     private $limit = 10;
    006     
    007     function Person(){
    008         parent::Controller();
    009         
    010         // load library
    011         $this->load->library(array('table','validation'));
    012         
    013         // load helper
    014         $this->load->helper('url');
    015         
    016         // load model
    017         $this->load->model('personModel','',TRUE);
    018     }
    019     
    020     function index($offset = 0){
    021         // offset
    022         $uri_segment = 3;
    023         $offset = $this->uri->segment($uri_segment);
    024         
    025         // load data
    026         $persons = $this->personModel->get_paged_list($this->limit, $offset)->result();
    027         
    028         // generate pagination
    029         $this->load->library('pagination');
    030         $config['base_url'] = site_url('person/index/');
    031         $config['total_rows'] = $this->personModel->count_all();
    032         $config['per_page'] = $this->limit;
    033         $config['uri_segment'] = $uri_segment;
    034         $this->pagination->initialize($config);
    035         $data['pagination'] = $this->pagination->create_links();
    036         
    037         // generate table data
    038         $this->load->library('table');
    039         $this->table->set_empty("&nbsp;");
    040         $this->table->set_heading('No', 'Name', 'Gender', 'Date of Birth (dd-mm-yyyy)', 'Actions');
    041         $i = 0 + $offset;
    042         foreach ($persons as $person){
    043             $this->table->add_row(++$i, $person->name, strtoupper($person->gender)=='M'? 'Male':'Female', date('d-m-Y',strtotime($person->dob)),
    044                 anchor('person/view/'.$person->id,'view',array('class'=>'view')).' '.
    045                 anchor('person/update/'.$person->id,'update',array('class'=>'update')).' '.
    046                 anchor('person/delete/'.$person->id,'delete',array('class'=>'delete','onclick'=>"return confirm('Are you sure want to delete this person?')"))
    047             );
    048         }
    049         $data['table'] = $this->table->generate();
    050         
    051         // load view
    052         $this->load->view('personList', $data);
    053     }
    054     
    055     function add(){
    056         // set validation properties
    057         $this->_set_fields();
    058         
    059         // set common properties
    060         $data['title'] = 'Add new person';
    061         $data['message'] = '';
    062         $data['action'] = site_url('person/addPerson');
    063         $data['link_back'] = anchor('person/index/','Back to list of persons',array('class'=>'back'));
    064     
    065         // load view
    066         $this->load->view('personEdit', $data);
    067     }
    068     
    069     function addPerson(){
    070         // set common properties
    071         $data['title'] = 'Add new person';
    072         $data['action'] = site_url('person/addPerson');
    073         $data['link_back'] = anchor('person/index/','Back to list of persons',array('class'=>'back'));
    074         
    075         // set validation properties
    076         $this->_set_fields();
    077         $this->_set_rules();
    078         
    079         // run validation
    080         if ($this->validation->run() == FALSE){
    081             $data['message'] = '';
    082         }else{
    083             // save data
    084             $person = array('name' => $this->input->post('name'),
    085                             'gender' => $this->input->post('gender'),
    086                             'dob' => date('Y-m-d', strtotime($this->input->post('dob'))));
    087             $id = $this->personModel->save($person);
    088             
    089             // set form input name="id"
    090             $this->validation->id = $id;
    091             
    092             // set user message
    093             $data['message'] = '<div>add new person success</div>';
    094         }
    095         
    096         // load view
    097         $this->load->view('personEdit', $data);
    098     }
    099     
    100     function view($id){
    101         // set common properties
    102         $data['title'] = 'Person Details';
    103         $data['link_back'] = anchor('person/index/','Back to list of persons',array('class'=>'back'));
    104         
    105         // get person details
    106         $data['person'] = $this->personModel->get_by_id($id)->row();
    107         
    108         // load view
    109         $this->load->view('personView', $data);
    110     }
    111     
    112     function update($id){
    113         // set validation properties
    114         $this->_set_fields();
    115         
    116         // prefill form values
    117         $person = $this->personModel->get_by_id($id)->row();
    118         $this->validation->id = $id;
    119         $this->validation->name = $person->name;
    120         $_POST['gender'] = strtoupper($person->gender);
    121         $this->validation->dob = date('d-m-Y',strtotime($person->dob));
    122         
    123         // set common properties
    124         $data['title'] = 'Update person';
    125         $data['message'] = '';
    126         $data['action'] = site_url('person/updatePerson');
    127         $data['link_back'] = anchor('person/index/','Back to list of persons',array('class'=>'back'));
    128     
    129         // load view
    130         $this->load->view('personEdit', $data);
    131     }
    132     
    133     function updatePerson(){
    134         // set common properties
    135         $data['title'] = 'Update person';
    136         $data['action'] = site_url('person/updatePerson');
    137         $data['link_back'] = anchor('person/index/','Back to list of persons',array('class'=>'back'));
    138         
    139         // set validation properties
    140         $this->_set_fields();
    141         $this->_set_rules();
    142         
    143         // run validation
    144         if ($this->validation->run() == FALSE){
    145             $data['message'] = '';
    146         }else{
    147             // save data
    148             $id = $this->input->post('id');
    149             $person = array('name' => $this->input->post('name'),
    150                             'gender' => $this->input->post('gender'),
    151                             'dob' => date('Y-m-d', strtotime($this->input->post('dob'))));
    152             $this->personModel->update($id,$person);
    153             
    154             // set user message
    155             $data['message'] = '<div>update person success</div>';
    156         }
    157         
    158         // load view
    159         $this->load->view('personEdit', $data);
    160     }
    161     
    162     function delete($id){
    163         // delete person
    164         $this->personModel->delete($id);
    165         
    166         // redirect to person list page
    167         redirect('person/index/','refresh');
    168     }
    169     
    170     // validation fields
    171     function _set_fields(){
    172         $fields['id'] = 'id';
    173         $fields['name'] = 'name';
    174         $fields['gender'] = 'gender';
    175         $fields['dob'] = 'dob';
    176         
    177         $this->validation->set_fields($fields);
    178     }
    179     
    180     // validation rules
    181     function _set_rules(){
    182         $rules['name'] = 'trim|required';
    183         $rules['gender'] = 'trim|required';
    184         $rules['dob'] = 'trim|required|callback_valid_date';
    185         
    186         $this->validation->set_rules($rules);
    187         
    188         $this->validation->set_message('required', '* required');
    189         $this->validation->set_message('isset', '* required');
    190         $this->validation->set_error_delimiters('<p>', '</p>');
    191     }
    192     
    193     // date_validation callback
    194     function valid_date($str)
    195     {
    196         if(!ereg("^(0[1-9]|1[0-9]|2[0-9]|3[01])-(0[1-9]|1[012])-([0-9]{4})$", $str))
    197         {
    198             $this->validation->set_message('valid_date', 'date format is not valid. dd-mm-yyyy');
    199             return false;
    200         }
    201         else
    202         {
    203             return true;
    204         }
    205     }
    206 }
    207 ?>
  7. View. create 3 files at CodeIgniter\system\application\views folder. personList.phpto list persons with pagination
    01 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    02 <html xmlns="http://www.w3.org/1999/xhtml">
    03 <head>
    04 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    05
    06 <title>SIMPLE CRUD APPLICATION</title>
    07
    08 <link href="<?php echo base_url(); ?>style/style.css" rel="stylesheet" type="text/css" />
    09
    10 </head>
    11 <body>
    12     <div class="content">
    13         <h1>Simple CRUD Application</h1>
    14         <div class="paging"><?php echo $pagination; ?></div>
    15         <div class="data"><?php echo $table; ?></div>
    16         <br />
    17         <?php echo anchor('person/add/','add new data',array('class'=>'add')); ?>
    18     </div>
    19 </body>
    20 </html>

    personEdit.php to add or update a person

    01 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    02 <html xmlns="http://www.w3.org/1999/xhtml">
    03 <head>
    04 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    05
    06 <title>SIMPLE CRUD APPLICATION</title>
    07
    08 <link href="<?php echo base_url(); ?>style/style.css" rel="stylesheet" type="text/css" />
    09
    10 <link href="<?php echo base_url(); ?>style/calendar.css" rel="stylesheet" type="text/css" />
    11 <script type="text/javascript" src="<?php echo base_url(); ?>script/calendar.js"></script>
    12
    13 </head>
    14 <body>
    15     <div class="content">
    16         <h1><?php echo $title; ?></h1>
    17         <?php echo $message; ?>
    18         <form method="post" action="<?php echo $action; ?>">
    19         <div class="data">
    20         <table>
    21             <tr>
    22                 <td width="30%">ID</td>
    23                 <td><input type="text" name="id" disabled="disable" class="text" value="<?php echo $this->validation->id; ?>"/></td>
    24                 <input type="hidden" name="id" value="<?php echo $this->validation->id; ?>"/>
    25             </tr>
    26             <tr>
    27                 <td valign="top">Name<span style="color:red;">*</span></td>
    28                 <td><input type="text" name="name" class="text" value="<?php echo $this->validation->name; ?>"/>
    29                 <?php echo $this->validation->name_error; ?></td>
    30             </tr>
    31             <tr>
    32                 <td valign="top">Gender<span style="color:red;">*</span></td>
    33                 <td><input type="radio" name="gender" value="M" <?php echo $this->validation->set_radio('gender', 'M'); ?>/> M
    34                     <input type="radio" name="gender" value="F" <?php echo $this->validation->set_radio('gender', 'F'); ?>/> F
    35                     <?php echo $this->validation->gender_error; ?></td>
    36             </tr>
    37             <tr>
    38                 <td valign="top">Date of birth (dd-mm-yyyy)<span style="color:red;">*</span></td>
    39                 <td><input type="text" name="dob" onclick="displayDatePicker('dob');" class="text" value="<?php echo $this->validation->dob; ?>"/>
    40                 <a href="javascript:void(0);" onclick="displayDatePicker('dob');"><img src="<?php echo base_url(); ?>style/images/calendar.png" alt="calendar" border="0"></a>
    41                 <?php echo $this->validation->dob_error; ?></td>
    42             </tr>
    43             <tr>
    44                 <td>&nbsp;</td>
    45                 <td><input type="submit" value="Save"/></td>
    46             </tr>
    47         </table>
    48         </div>
    49         </form>
    50         <br />
    51         <?php echo $link_back; ?>
    52     </div>
    53 </body>
    54 </html>

    personView.php to view a person details

    01 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    02 <html xmlns="http://www.w3.org/1999/xhtml">
    03 <head>
    04 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    05
    06 <title>SIMPLE CRUD APPLICATION</title>
    07
    08 <link href="<?php echo base_url(); ?>style/style.css" rel="stylesheet" type="text/css" />
    09
    10 </head>
    11 <body>
    12     <div class="content">
    13         <h1><?php echo $title; ?></h1>
    14         <div class="data">
    15         <table>
    16             <tr>
    17                 <td width="30%">ID</td>
    18                 <td><?php echo $person->id; ?></td>
    19             </tr>
    20             <tr>
    21                 <td valign="top">Name</td>
    22                 <td><?php echo $person->name; ?></td>
    23             </tr>
    24             <tr>
    25                 <td valign="top">Gender</td>
    26                 <td><?php echo strtoupper($person->gender)=='M'? 'Male':'Female' ; ?></td>
    27             </tr>
    28             <tr>
    29                 <td valign="top">Date of birth (dd-mm-yyyy)</td>
    30                 <td><?php echo date('d-m-Y',strtotime($person->dob)); ?></td>
    31             </tr>
    32         </table>
    33         </div>
    34         <br />
    35         <?php echo $link_back; ?>
    36     </div>
    37 </body>
    38 </html>
  8. Style. put stylesheet at CodeIgniter\style\style.css and style’s images at CodeIgniter\style\images folder

    001 body {
    002     font-family:tahoma;
    003     padding:0px;
    004     margin:0px;
    005     background:#f5f5f5
    006 }
    007
    008 div.content {
    009     padding:10px 20px;
    010 }
    011 div.content h1 {
    012     font-size:18pt;
    013     border-bottom:5px solid #a00;
    014     padding:0px;
    015     margin:10px 0px 20px;
    016     width:80%;
    017 }
    018
    019 div.content div.data table {
    020     border:2px solid #000;
    021     background:#fff;
    022     width:80%;
    023 }
    024 div.content div.data table td {
    025     font-size:10pt;
    026     padding:5px 10px;
    027     border-bottom:1px solid #ddd;
    028     text-align: left;
    029 }
    030 div.content div.data table th {
    031     text-align: left;
    032     font-size: 8pt;
    033     padding: 10px 10px 7px;
    034     text-transform: uppercase;
    035     color: #fff;
    036     background:url(images/head.gif) left -5px repeat-x;
    037 }
    038
    039 div.paging {
    040     font-size: 9pt;
    041     margin:5px 0px;
    042 }
    043 div.paging a {
    044     color:#900;
    045     text-transform: uppercase;
    046     text-decoration: none;
    047 }
    048 div.paging a:hover {
    049     color:#c00;
    050 }
    051 div.paging b {
    052     color:#900;
    053 }
    054
    055 div.success {
    056     font-size:14pt;
    057     background:url(images/accept.png) left 5px no-repeat;
    058     padding:0px;
    059     padding-left:20px;
    060     margin:0px 0px 10px;
    061     color:#060;
    062     width:80%;
    063 }
    064
    065 a.update, a.delete, a.add, a.view, a.back {
    066     font-size: 9pt;
    067     color:#900;
    068     font-wight:bold;
    069     padding-left:20px;
    070     text-decoration: none;
    071 }
    072 a.update {
    073     background:url(images/update.png) left center no-repeat;
    074 }
    075 a.delete {
    076     background:url(images/delete.png) left center no-repeat;
    077 }
    078 a.add {
    079     background:url(images/add.png) left center no-repeat;
    080 }
    081 a.view {
    082     background:url(images/view.png) left center no-repeat;
    083 }
    084 a.back {
    085     background:url(images/prev.gif) left center no-repeat;
    086 }
    087 a.update:hover, a.delete:hover, a.add:hover, a.view:hover {
    088     color:#000;
    089 }
    090
    091 input.text {
    092     border:2px solid #aaa;
    093 }
    094
    095 .error {
    096     background: #FBE6F2 none repeat scroll 0 0;
    097     border: 1px solid #D893A1;
    098     color: #333333;
    099     margin: 5px 0 0;
    100     padding: 5px;
    101     font-size: 10px;
    102     font-family: Lucida Grande,Verdana,Geneva,Sans-serif;
    103 }
  9. Script. put script at CodeIgniter\script folder
  10. Done. Lets preview what should we have by now.
list_of_personList of persons with pagination

add_new_personAdd new person

update_personUpdate person

view_personView person details

error_validationError on validation

Download Simple CRUD Application. Happy Programming!!

Cake PHP 10 Topics to read

Posted: January 23, 2012 in Cakephp