CodeIgniter Forums
How to instance db class on 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: How to instance db class on helper (/showthread.php?tid=18588)



How to instance db class on helper - El Forum - 05-11-2009

[eluser]pengenbelajarCI[/eluser]
Hi, I'm newbie here. And now I'm trying to make a helper. The function in this helper is to show the sitename from config table on database.

Helper
Code:
function sitename($db) {
    $db->select('sitename');
    $query = $db->get('config');    
    $row = $query->row();
    return $row->sitename;    
}

Controller
Code:
class Front extends Controller {

    function Front()
    {
        parent::Controller();    
    }
    
    function index()
    {
        $data['sitename'] = sitename($this->db);
        $this->load->view('main',$data);
    }
}

Is there anyway to make the function in the model just sitename() not sitename($db), so on the controller just type $data['sitename'] = sitename(); not $data['sitename'] = sitename($this->db);.


Sorry for my bad English


How to instance db class on helper - El Forum - 05-11-2009

[eluser]Thorpe Obazee[/eluser]
here's a sample of accessing the database with a helper

Code:
if ( ! function_exists('the_author'))
{
    function the_author($uri)
    {
        $ci =& get_instance();
        $ci->db->select('users.username as users_username');
        $ci->db->join('posts', 'posts.user_id = users.id');
        $query = $ci->db->get_where('users', array('posts.uri' => $uri));
        $user = $query->row();
        echo $user->users_username;
    }
}

usage:
Code:
the_author('the post');



How to instance db class on helper - El Forum - 05-11-2009

[eluser]pengenbelajarCI[/eluser]
thanks.
just put $ci =& get_instance() at the function.

solved