Sunday, 25 September 2016

9. Error Handling

Error Handling


Many times, while using application, we come across errors. It is very annoying for the users if the errors are not handled properly. CodeIgniter provides an easy error handling mechanism.
You would like the messages to be displayed, when the application is in developing mode rather than in production mode as the error messages can be solved easily at the developing stage.
The environment of your application can be changed, by changing the line given below from index.php file. This can be set to anything but normally there are three values (development, test, production) used for this purpose.
define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');
Different environment will require different levels of error reporting. By default, development mode will display errors and testing and live mode will hide them. CodeIgniter provides three functions as shown below to handle errors.
  • show_error() function displays errors in HTML format at the top of the screen.
Syntax
show_error($message, $status_code, $heading = 'An Error Was Encountered')
Parameters
  • $message (mixed) − Error message
  • $status_code (int) − HTTP Response status code
  • $heading (string) − Error page heading
Return Type
mixed
  • show_404() function displays error if you are trying to access a page which does not exist.
Syntax
show_404($page = '', $log_error = TRUE)
Parameters
  • $page (string) – URI string
  • $log_error (bool) – Whether to log the error
Return Type
void
  • log_message() function is used to write log messages. This is useful when you want to write custom messages.
Syntax
log_message($level, $message, $php_error = FALSE)
Parameters
  • $level (string) − Log level: ‘error’, ‘debug’ or ‘info’
  • $message (string) − Message to log
  • $php_error (bool) − Whether we’re logging a native PHP error message
Return Type
void
Logging can be enabled in application/config/config.php file. Given below is the screenshot of config.php file, where you can set threshold value.
/*
|--------------------------------------------------------------------------------
|   Error Logging Threshold
|--------------------------------------------------------------------------------
| You can enable error logging by setting a threshold over zero. The 
| threshold determines what gets logged. Threshold options are:
|
|   0 = Disable logging, Error logging TURNED OFF
|   1 = Error Message (including PHP errors)
|   2 = Debug Message
|   3 = Informational Messages
|   4 = All Messages
|
| You can also pass an array with threshold levels to show individual error types
|
|   array(2) = Debug Message, without Error Messages
| For a live site you'll usually only enable Errors (1) to be logged otherwise 
| your log files will fill up very fast.
|
*/
$config['log_threshold'] = 0;
You can find the log messages in application/log/. Make sure that this directory is writable before you enable log files.
Various templates for error messages can be found inapplication/views/errors/cli or application/views/errors/html.

8. Libraries

Libraries


The essential part of a CodeIgniter framework is its libraries. It provides a rich set of libraries, which indirectly increase the speed of developing an application. The system library is located at system/libraries. All we need to do is to load the library that we want to use. The library can be loaded as shown below −
$this->load->library('class name');
Where class name is the name of the library that we want to load. If we want to load multiple libraries, then we can simply pass an array as argument to library() function as shown below −
$this->load->library(array('email', 'table'));

Library Classes

The library classes are located in system/libraries. Each class has various functions to simplify the developing work. Following table shows the names of the library class and its description.


Creating Libraries

CodeIgniter has rich set of libraries, which you can find insystem/libraries folder but CodeIgniter is not just limited to system libraries, you can create your own libraries too, which can be stored inapplication/libraries folder. You can create libraries in three ways.
  • Create new library
  • Extend the native library
  • Replace the native library

Create New Library

While creating new library one should keep in mind, the following things −
  • The name of the file must start with a capital letter e.g. Mylibrary.php
  • The class name must start with a capital letter e.g. class Mylibrary
  • The name of the class and name of the file must match.
Mylibrary.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
   
   class Mylibrary {
 
      public function some_function() {
      }
   }
 
/* End of file Mylibrary.php */
Loading the Custom Library
The above library can be loaded by simply executing the following line in your controller.
$this->load->library(‘mylibrary’);
mylibrary is the name of your library and you can write it in lowercase as well as uppercase letters. Use the name of the library without “.php” extension. After loading the library, you can also call the function of that class as shown below.
$this->mylibrary->some_function();

Extend the Native Library

Sometimes, you may need to add your own functionality to the library provided by CodeIgniter. CodeIgniter provides facility by which you can extend the native library and add your own functions. To achieve this, you must extend the class of native library class. For example if you want to extend the Email library then it can be done as shown below −
Class MY_Email extends CI_Email { 
}
Here, in the above example, MY_Email class is extending the native library’s email class CI_Email. This library can be loaded by the standard way of loading email library. Save the above code in file My_Email.php

Replace the Native Library

In some situations, you do not want to use the native library the way it works and want to replace it with your own way. This can be done by replacing the native library. To achieve this, you just need to give the same class name as it is named in native library. For example, if you want to replace the Email class, then use the code as shown below. Save your file name with Email.php and give a class name toCI_Email.
Email.php
Class CI_Email { 
}

7. Working with Database

Working with Database



Like any other framework, we need to interact with the database very often and CodeIgniter makes this job easy for us. It provides rich set of functionalities to interact with database.
In this section, we will understand how the CRUD (Create, Read, Update, Delete) functions work with CodeIgniter. We will use studtable to select, update, delete, and insert the data in stud table.
Table Name: stud
roll_noint(11)
Namevarchar(30)

Connecting to a Database

We can connect to database in the following two way −
  • Automatic Connecting − Automatic connection can be done by using the file application/config/autoload.php. Automatic connection will load the database for each and every page. We just need to add the database library as shown below −
$autoload['libraries'] = array(‘library’);
  • Manual Connecting − If you want database connectivity for only some of the pages, then we can go for manual connecting. We can connect to database manually by adding the following line in any class.
$this->load->database();
Here, we are not passing any argument because everything is set in the database config file application/config/database.php

Inserting a Record

To insert a record in the database, the insert() function is used as shown in the following table −
Syntax
insert([$table = ''[, $set = NULL[, $escape = NULL]]])
Parameters
  • $table (string) − Table name
  • $set (array) − An associative array of field/value pairs
  • $escape (bool) − Whether to escape values and identifiers
Returns
TRUE on success, FALSE on failure
Return Type
bool
The following example shows how to insert a record in stud table. The $data is an array in which we have set the data and to insert this data to the table stud, we just need to pass this array to the insert function in the 2nd argument.
$data = array( 
   'roll_no' => ‘1’, 
   'name' => ‘Virat’ 
); 

$this->db->insert("stud", $data);

Updating a Record

To update a record in the database, the update() function is used along with set() and where() functions as shown in the tables below. The set() function will set the data to be updated.
Syntax
set($key[, $value = ''[, $escape = NULL]])
Parameters
  • $key (mixed) − Field name, or an array of field/value pairs
  • $value (string) − Field value, if $key is a single field
  • $escape (bool) − Whether to escape values and identifiers
Returns
CI_DB_query_builder instance (method chaining)
Return Type
CI_DB_query_builder
The where() function will decide which record to update.
Syntax
where($key[, $value = NULL[, $escape = NULL]])
Parameters
  • $key (mixed) − Name of field to compare, or associative array
  • $value (mixed) − If a single key, compared to this value
  • $escape (bool) − Whether to escape values and identifiers
Returns
DB_query_builder instance
Return Type
object
Finally, the update() function will update data in the database.
Syntax
update([$table = ''[, $set = NULL[, $where = NULL[, $limit = NULL]]]])
Parameters
  • $table (string) − Table name
  • $set (array) − An associative array of field/value pairs
  • $where (string) − The WHERE clause
  • $limit (int) − The LIMIT clause
Returns
TRUE on success, FALSE on failure
Return Type
bool
$data = array( 
   'roll_no' => ‘1’, 
   'name' => ‘Virat’ 
); 

$this->db->set($data); 
$this->db->where("roll_no", ‘1’); 
$this->db->update("stud", $data);

Deleting a Record

To delete a record in the database, the delete() function is used as shown in the following table −
Syntax
delete([$table = ''[, $where = ''[, $limit = NULL[, $reset_data = TRUE]]]])
Parameters
  • $table (mixed) − The table(s) to delete from; string or array
  • $where (string) − The WHERE clause
  • $limit (int) − The LIMIT clause
  • $reset_data (bool) − TRUE to reset the query “write” clause
Returns
CI_DB_query_builder instance (method chaining) or FALSE on failure
Return Type
mixed
Use the following code to to delete a record in the stud table. The first argument indicates the name of the table to delete record and the second argument decides which record to delete.
$this->db->delete("stud", "roll_no = 1");

Selecting a Record

To select a record in the database, the get function is used, as shown in the following table −
Syntax
get([$table = ''[, $limit = NULL[, $offset = NULL]]])
Parameters
  • $table (string) − The table to query array
  • $limit (int) − The LIMIT clause
  • $offset (int) − The OFFSET clause
Returns
CI_DB_result instance (method chaining)
Return Type
CI_DB_result
Use the following code to get all the records from the database. The first statement fetches all the records from “stud” table and returns the object, which will be stored in $query object. The second statement calls the result() function with $query object to get all the records as array.
$query = $this->db->get("stud"); 
$data['records'] = $query->result();

Closing a Connection

Database connection can be closed manually, by executing the following code −
$this->db->close(); 

Example

Create a controller class called Stud_controller.php and save it atapplication/controller/Stud_controller.php
Here is a complete example, wherein all of the above-mentioned operations are performed. Before executing the following example, create a database and table as instructed at the starting of this chapter and make necessary changes in the database config file stored at application/config/database.php
<?php 
   class Stud_controller extends CI_Controller {
 
      function __construct() { 
         parent::__construct(); 
         $this->load->helper('url'); 
         $this->load->database(); 
      } 
  
      public function index() { 
         $query = $this->db->get("stud"); 
         $data['records'] = $query->result(); 
   
         $this->load->helper('url'); 
         $this->load->view('Stud_view',$data); 
      } 
  
      public function add_student_view() { 
         $this->load->helper('form'); 
         $this->load->view('Stud_add'); 
      } 
  
      public function add_student() { 
         $this->load->model('Stud_Model');
   
         $data = array( 
            'roll_no' => $this->input->post('roll_no'), 
            'name' => $this->input->post('name') 
         ); 
   
         $this->Stud_Model->insert($data); 
   
         $query = $this->db->get("stud"); 
         $data['records'] = $query->result(); 
         $this->load->view('Stud_view',$data); 
      } 
  
      public function update_student_view() { 
         $this->load->helper('form'); 
         $roll_no = $this->uri->segment('3'); 
         $query = $this->db->get_where("stud",array("roll_no"=>$roll_no));
         $data['records'] = $query->result(); 
         $data['old_roll_no'] = $roll_no; 
         $this->load->view('Stud_edit',$data); 
      } 
  
      public function update_student(){ 
         $this->load->model('Stud_Model');
   
         $data = array( 
            'roll_no' => $this->input->post('roll_no'), 
            'name' => $this->input->post('name') 
         ); 
   
         $old_roll_no = $this->input->post('old_roll_no'); 
         $this->Stud_Model->update($data,$old_roll_no); 
   
         $query = $this->db->get("stud"); 
         $data['records'] = $query->result(); 
         $this->load->view('Stud_view',$data); 
      } 
  
      public function delete_student() { 
         $this->load->model('Stud_Model'); 
         $roll_no = $this->uri->segment('3'); 
         $this->Stud_Model->delete($roll_no); 
   
         $query = $this->db->get("stud"); 
         $data['records'] = $query->result(); 
         $this->load->view('Stud_view',$data); 
      } 
   } 
?>
Create a model class called Stud_Model.php and save it inapplication/models/Stud_Model.php
<?php 
   class Stud_Model extends CI_Model {
 
      function __construct() { 
         parent::__construct(); 
      } 
   
      public function insert($data) { 
         if ($this->db->insert("stud", $data)) { 
            return true; 
         } 
      } 
   
      public function delete($roll_no) { 
         if ($this->db->delete("stud", "roll_no = ".$roll_no)) { 
            return true; 
         } 
      } 
   
      public function update($data,$old_roll_no) { 
         $this->db->set($data); 
         $this->db->where("roll_no", $old_roll_no); 
         $this->db->update("stud", $data); 
      } 
   } 
?> 
Create a view file called Stud_add.php and save it inapplication/views/Stud_add.php
<!DOCTYPE html> 
<html lang = "en">
 
   <head> 
      <meta charset = "utf-8"> 
      <title>Students Example</title> 
   </head> 
   <body> 
         <?php 
            echo form_open('Stud_controller/add_student');
            echo form_label('Roll No.'); 
            echo form_input(array('id'=>'roll_no','name'=>'roll_no')); 
            echo "<br/>"; 
   
            echo form_label('Name'); 
            echo form_input(array('id'=>'name','name'=>'name')); 
            echo "<br/>"; 
   
            echo form_submit(array('id'=>'submit','value'=>'Add')); 
            echo form_close(); 
         ?> 
   </body>
</html>
Create a view file called Stud_edit.php and save it inapplication/views/Stud_edit.php
<!DOCTYPE html> 
<html lang = "en">
 
   <head> 
      <meta charset = "utf-8"> 
      <title>Students Example</title> 
   </head> 
 
   <body> 
      <form method = "" action = "">
  
         <?php 
            echo form_open('Stud_controller/update_student'); 
            echo form_hidden('old_roll_no',$old_roll_no); 
            echo form_label('Roll No.'); 
            echo form_input(array('id'=>'roll_no',
               'name'=>'roll_no','value'=>$records[0]->roll_no)); 
            echo "<br/>"; 
    
            echo form_label('Name'); 
            echo form_input(array('id'=>'name','name'=>'name',
               'value'=>$records[0]->name)); 
            echo "<br/>"; 
    
            echo form_submit(array('id'=>'submit','value'=>'Edit')); 
            echo form_close();
         ?> 
   
      </form> 
   </body>
 
</html>
Create a view file called Stud_view.php and save it inapplication/views/Stud_view.php
<!DOCTYPE html> 
<html lang = "en">
 
   <head> 
      <meta charset = "utf-8"> 
      <title>Students Example</title> 
   </head>
 
   <body> 
      <a href = "<?php echo base_url(); ?>
         index.php/stud/add_view">Add</a>
  
      <table border = "1"> 
         <?php 
            $i = 1; 
            echo "<tr>"; 
            echo "<td>Sr#</td>"; 
            echo "<td>Roll No.</td>"; 
            echo "<td>Name</td>"; 
            echo "<td>Edit</td>"; 
            echo "<td>Delete</td>"; 
            echo "<tr>"; 
    
            foreach($records as $r) { 
               echo "<tr>"; 
               echo "<td>".$i++."</td>"; 
               echo "<td>".$r->roll_no."</td>"; 
               echo "<td>".$r->name."</td>"; 
               echo "<td><a href = '".base_url()."index.php/stud/edit/"
                  .$r->roll_no."'>Edit</a></td>"; 
               echo "<td><a href = '".base_url()."index.php/stud/delete/"
                  .$r->roll_no."'>Delete</a></td>"; 
               echo "<tr>"; 
            } 
         ?>
      </table> 
  
   </body>
 
</html>
Make the following change in the route file atapplication/config/routes.php and add the following line at the end of file.
$route['stud'] = "Stud_controller"; 
$route['stud/add'] = 'Stud_controller/add_student'; 
$route['stud/add_view'] = 'Stud_controller/add_student_view'; 
$route['stud/edit/(\d+)'] = 'Stud_controller/update_student_view/$1'; 
$route['stud/delete/(\d+)'] = 'Stud_controller/delete_student/$1';
Now, let us execute this example by visiting the following URL in the browser. Replace the yoursite.com with your URL.
http://yoursite.com/index.php/stud