Tuesday 3 November 2015

Common select query in Codeigniter (Single Function)

This is the codeigniter function for common select query that you need to place in model. and call it from controller. 

function db_select($select, $from, $where = array(), $group = array(), $order = '', $having = '', $limit =array(), $result_way = 'all', $echo = 0) {
        $result = array();
        $this->db->select($select);
        $this->db->from($from);
        if (!empty($where)) {            $this->db->where($where);        }
        if (!empty($group)) {            $this->db->group_by($group);        }
        if ($order != '') {            $this->db->order_by($order);        }
        if (isset($limit[0])) {                       $this->db->limit($limit[0]);//example $limit[0] = "0,10" where  0 is for offset and 10 for limit
        }
        $temp = $this->db->get();
        switch ($result_way) {
            case 'row':
                $result = $temp->row();
                break;
            case 'row_array':
                $result = $temp->row_array();
                break;
            case 'count':
                $result = $temp->num_rows();
                break;
            default:
                $result = $temp->result_array();
                break;
        }
        if ($echo == 1) {
            echo $this->db->last_query();
            exit;
        }        return $result;    }
suppose your model name is say “basic_model” than you need to call this function in controller like..

$t = $this->basic->db_select('user_id', 'tbl_user', $wh=array("user_id"=>1), array("user_id"), 'user_id desc', '', '', 'row_array');

Parameter understanding :
$select           : string of database table column in comma separated or * for all column
$from             : string of database table name
$where          : An associative array in which array key should be table column and array value would be table column value
$group          : an array of database column e.g array(“user_id”) so it gives output as group by user_id
$order           : string of database column with ASC or DESC parameter e.g ‘user_id DESC’
$having        : string of database column with condition say sum(‘coin’) > 0
$limit            : an array of limit string e.g array(“10,0″) so this gives output as limit 0,10
$result_way : string for output way
$echo           : 0 or 1 . if you want the query string from codeigniter than set this value as 1
By changing the query guide functionality you can use this function for other framework or in cms.

No comments:

Post a Comment

Simple CRUD in Laravel Framework

Creating, reading, updating, and deleting resources is used in pretty much every application. Laravel helps make the process easy using re...