CodeIgniter Forums
Cannot query database in custom_helper? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Cannot query database in custom_helper? (/showthread.php?tid=1840)



Cannot query database in custom_helper? - El Forum - 06-30-2007

[eluser]java[/eluser]
I have a function placed in custom_helper file :
Code:
function getCityName($id)
{
    $query = $this->db->getwhere('thanhpho', array('ThanhPhoID' => $id));
    $row = $query->row();
    return $row->Ten;
}
i want it automatically called in my view. But the view generated error:
Quote:Fatal error: Call to a member function on a non-object in d:\www\hoahau\system\application\helpers\custom_helper.php on line 181
and line 181 is my query command in function above.
What's the wrong in my code? Please tell.
Thanks for any response


Cannot query database in custom_helper? - El Forum - 06-30-2007

[eluser]marcoss[/eluser]
[quote author="java" date="1183211431"]I have a function placed in custom_helper file :
Code:
function getCityName($id)
{
    $query = $this->db->getwhere('thanhpho', array('ThanhPhoID' => $id));
    $row = $query->row();
    return $row->Ten;
}
i want it automatically called in my view. But the view generated error:
Quote:Fatal error: Call to a member function on a non-object in d:\www\hoahau\system\application\helpers\custom_helper.php on line 181
and line 181 is my query command in function above.
What's the wrong in my code? Please tell.
Thanks for any response[/quote]

You have to instantiate CI if you want to use it out the flow, so you should go as follows,

Code:
$CI =& get_instance();
    
    function getCityName($id){
        $query = $CI->db->getwhere('thanhpho', array('ThanhPhoID' => $id));
        $row = $query->row();
        return $row->Ten;
    }



Cannot query database in custom_helper? - El Forum - 07-01-2007

[eluser]java[/eluser]
I tried to instantiate CI but it still generate an error. I dont know it's not understand my query command.


Cannot query database in custom_helper? - El Forum - 07-01-2007

[eluser]OwanH[/eluser]
[quote author="java" date="1183358263"]I tried to instantiate CI but it still generate an error. I dont know it's not understand my query command.[/quote]

Make sure you are loading the Active Record class. In the database configuration file located at:

application/config/database.php

make sure the following variable is set to TRUE:

Code:
$db['default']['active_r'] = TRUE;

where 'default' is the name of your active database group.