php CodeIgniter 辅助函数可以使用数据库函数吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15888332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:08:16  来源:igfitidea点击:

Can CodeIgniter Helper Functions use database functions?

phpcodeigniterrecursioncontrollerhelper

提问by Rorrik

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?

我的 CodeIgniter Controller 函数之一需要调用递归函数作为其功能的一部分。如果我把它放在控制器类中,函数调用就会阻塞,如果我把它放在类之外,它就无法访问数据库函数($this->db->get())。使它成为辅助函数可以解决这个问题吗?

回答by Svetoslav

You can get instance:

你可以得到实例:

 $CI =& get_instance();

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

之后,您将能够$CI->db用于查询..

回答by Sangar82

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

回答by Naveed Ramzan

We can define a function in helper

我们可以在 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.

回答by kamal

 //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/得到它