Search code examples
phpsqlcodeigniteractiverecordcodeigniter-2

base query method in CodeIgniter


Im trying to create a base query that I can then use later to add grouping or filters

simplified example:

function baseQuery()
{
    $query = $this->db->select('*')
    return $query;
}

function queryWhere($value)
{
    $query = $this->baseQuery();
    $query->where($value)
    $result = $query->get();

    return $result
}

What is the correct way to do this in CodeIgniter?


Solution

  • Your code needs some dynamic values like table and field names for extending single purpose of query
    Take a look on example

    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    class Testing extends CI_Controller {
    
        public function baseQuery($fields,$tableName)
        {
            $query = $this->db;
            $query->select($fields);
            $query->from($tableName);
            return $query;
        }
    
        public function queryWhere($whereCondition)
        {
            $query = $this->baseQuery('*','tablename');
            $query->where($whereCondition);
            $result = $query->get();
            return $result;
        }
        public function index() {
    
            $query = $this->queryWhere("id > 0");
            $data = $query->result_array();
            print_r($data);
        }  
    
    }