Can CodeIgniter Helper Functions use database functions?

前提是你 提交于 2019-12-03 16:30:27

问题


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?


回答1:


You can get instance:

 $CI =& get_instance();

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




回答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');



回答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.



回答4:


 //Select Data:

$this->db->select(‘fieldname seperated by commas’);

$this->db->from(‘table’);

$query = $this->db->get();

$results=$query->result() ;

//Joins:

$this->db->select(‘*’);
$this->db->from(‘table1′);
$this->db->join(‘table2′, ‘table2.id = table1.id’);

$query = $this->db->get();

We may get it from http://skillrow.com/codeignitor-database-functions/



来源:https://stackoverflow.com/questions/15888332/can-codeigniter-helper-functions-use-database-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!