Using the database from inside a helper (CodeIgniter)

I have some custom functions that I store in a helper in CodeIgniter.

Some of those functions need to use the database, and to do so you have to explicitly tell the function to load the Code Igniter framework and database class.

Its pretty simple when you know how, but it took quite a while to work it out.

function get_user_full_name($userId) {

    //the database functions can not be called from within the helper
    //so we have to explicitly load the functions we need in to an object
    //that I will call ci. then we use that to access the regular stuff.
    $ci=& get_instance();

    //select the required fields from the database
    $ci->db->select('firstName, lastName');

    //tell the db class the criteria
    $ci->db->where('userId', $userId);

    //supply the table name and get the data
    $row = $ci->db->get('user')->row();

    //get the full name by concatinating the first and last names
    $fullName = $row->firstName . " " . $row->lastName;

    // return the full name;
    return $fullName;



Moved from my other website,

Leave a Reply

Your email address will not be published. Required fields are marked *