Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can CodeIgniter Helper Functions use database functions?

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?

like image 244
Rorrik Avatar asked Apr 08 '13 20:04

Rorrik


People also ask

What is helper function in CodeIgniter?

They are simple, procedural functions. Each helper function performs one specific task, with no dependence on other functions. CodeIgniter does not load Helper Files by default, so the first step in using a Helper is to load it. Once loaded, it becomes globally available in your controller and views.

What is difference between Library and helper in CodeIgniter?

The main difference between Helper and Library in CodeIgniter is that Helper is a file with a set of functions in a particular category and is not written in Object Oriented format, while the Library is a class with a set of functions that allows creating an instance of that class and is written in Object Oriented ...

How does helper function work?

A helper function is a function that performs part of the computation of another function. Helper functions are used to make your programs easier to read by giving descriptive names to computations. They also let you reuse computations, just as with functions in general.


3 Answers

You can get instance:

 $CI =& get_instance();

After that you will be able to use $CI->db for queries..

like image 99
Svetoslav Avatar answered Nov 06 '22 04:11

Svetoslav


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');
like image 28
Sangar82 Avatar answered Nov 06 '22 05:11

Sangar82


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.
like image 39
Naveed Ramzan Avatar answered Nov 06 '22 03:11

Naveed Ramzan