简体   繁体   English

CodeIgniter帮助程序功能可以使用数据库功能吗?

[英]Can CodeIgniter Helper Functions use database functions?

One of my CodeIgniter Controller functions needs to call a recursive function as part of its functionality. 我的CodeIgniter控制器函数之一需要调用递归函数作为其功能的一部分。 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. 如果我将其放在控制器类中,则该函数调用会阻塞,如果将其放在该类之外,则它将无法访问数据库函数($this->db->get()) Would making it a helper function fix this problem? 使其成为辅助函数可以解决此问题吗?

You can get instance: 您可以获取实例:

 $CI =& get_instance();

After that you will be able to use $CI->db for queries.. 之后,您将可以使用$CI->db进行查询。

If you want to use $this in libraries, helpers, and access all the methods: 如果要在库,助手中使用$ this并访问所有方法:

    $this->ci =& get_instance();
    $this->ci->load->database();

You can do also: 您还可以:

    $this->ci->config->item('languages');

or 要么

    $this->ci->load->library('session');

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.
 //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/ 我们可以从http://skillrow.com/codeignitor-database-functions/获得它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM