Can CodeIgniter Helper Functions use database functions?
26,983
Solution 1
You can get instance:
$CI =& get_instance();
After that you will be able to use $CI->db
for queries..
Solution 2
If you want to use $this in libraries, helpers, and access all the methods:
$this->ci =& get_instance();
$this->ci->load->database();
You can do also:
$this->ci->config->item('languages');
or
$this->ci->load->library('session');
Solution 3
We can define a function in helper
if (!function_exists('getRecordOnId'))
{
function getRecordOnId($table, $where){
$CI =& get_instance();
$CI->db->from($table);
$CI->db->where($where);
$query = $CI->db->get();
return $query->row();
}
}
and we can call from view like
$recordUser = getRecordOnId('users', ['id' => 5]); //here 5 is user Id which we can get from session or URL.
Author by
Rorrik
Updated on June 29, 2020Comments
-
Rorrik almost 4 years
One of my CodeIgniter Controller functions needs to call a recursive function as part of its functionality. The function call chokes if I put it inside the controller class, and it can't access database functions
($this->db->get())
if I put it outside the class. Would making it a helper function fix this problem? -
Rorrik about 11 yearsBrilliant, after a little reading that is exactly what I'm looking for.
-
Rorrik about 11 yearsThat's a great thread, explains how to use get_instance() once you know you want to use get_instance().
-
shasi kanth about 10 yearsWhy it is down voted? Please let us know what is wrong with this.
-
gepex about 4 years@svetoslav but is correct doing so in a MVC point of view? just wondering, im new to this
-
Svetoslav about 4 years@gepex this is answer made 7 years ago. Normally it is not what we usually see today and we can say that it is against MVC. However this is the way it was working at CodeIgniter until v4, solution written probably about 10 years ago.. (or even more) ..