In this article, We will discuss how to create custom helper in CodeIgniter. CodeIgniter allows the creation of a custom helper. So we can easily create a custom helper. we will take the latest example and learn how to use a custom helper in CodeIgniter. so let’s follow the below step.
first, we will create a helper file in the “application/helpers/commonfunction_helper.php”. put some code in this file. here in this file. we will get the student all detail using the custom helper function.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
* get_all_rows
*
*/
function get_all_student_rows()
{
$CI =& get_instance();
$CI->db->select();
$query = $CI->db->get('students');
//echo $CI->db->last_query();die;
return $query->result_array(); // This will return array
}
?>
Now, we will load the custom helper so we will open the application/config/autoload.php file and add the helper name to the helper array.
/*
| -------------------------------------------------------------------
| Auto-load Helper Files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['helper'] = array('url', 'file');
*/
$autoload['helper'] = array('commonfunction_helper');
now, we can use the custom helper function in Controller or Views. we can get the student detail in Controller or Views using the call get_all_rows helper function.
Controller Example
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Student extends CI_Controller {
function __construct()
{
parent::__construct();
}
public function index()
{
$student_detail = get_all_student_rows();
echo "<pre>";
print_r(student_detail);
echo "</pre>";
}
}
View Example
<?php
$student_detail = get_all_student_rows();
echo "<pre>";
print_r(student_detail);
echo "</pre>";
?>
So finally, I hope you like this article.