[英]Is it a good practice to use database queries in helper functions in codeigniter?
[英]Can CodeIgniter Helper Functions use database functions?
我的CodeIgniter控制器函數之一需要調用遞歸函數作為其功能的一部分。 如果我將其放在控制器類中,則該函數調用會阻塞,如果將其放在該類之外,則它將無法訪問數據庫函數($this->db->get())
。 使其成為輔助函數可以解決此問題嗎?
您可以獲取實例:
$CI =& get_instance();
之后,您將可以使用$CI->db
進行查詢。
如果要在庫,助手中使用$ this並訪問所有方法:
$this->ci =& get_instance();
$this->ci->load->database();
您還可以:
$this->ci->config->item('languages');
要么
$this->ci->load->library('session');
我們可以在助手中定義一個函數
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();
}
}
我們可以從像
$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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.