Jay Modi
Jay Modi

Reputation: 639

Mysql statement not working in CodeIgniter Model class

Currently I'm trying to retrieve all the entries from my data that are within a particular timeframe. To do this I have a method in my model class with the following statement:

public function get_records_all($st_date,$end_date){
        $sql = SELECT
            *
            FROM `crm_listings`  
            WHERE added_date BETWEEN '" . $st_date . "' AND '".$end_date."'
            ORDER BY `added_date` DESC;
            $response = $this->db->query($sql);
            echo $response;
     }

And in my controller class I'm using the following statement to show the output:

function fetch_status(){
            $startDate = '';
            $endDate = '';
            $this->load->model('crm/user_model');
  
            if($this->input->post('startDate')){
              $startDate = $this->input->post('startDate');
            }
            if($this->input->post('endDate')){
               $endDate = $this->input->post('endDate');
             }

             $data_all = $this->user_model->get_records_all($startDate,$endDate);
}

But this gives me the following error:

enter image description here

Upvotes: 1

Views: 133

Answers (3)

Muhammad Nadeem
Muhammad Nadeem

Reputation: 31

You forgot to add ->result() after $this->db->query($sql) like:

$response = $this->db->query($sql)->result();

However you can also use Query Builder like

public function get_records_all($st_date,$end_date){

     return $this->db->where('added_date >=', $st_date)
             ->where('added_date <=', $end_date);
             ->order_by('added_date', 'DESC');
             ->get('crm_listings')
             ->result();
}

Upvotes: 0

adam
adam

Reputation: 367

if you insist using db->query change your get_records_all() response to return $response; then you can use $data_all as and object like this

foreach($data_all as $data) {
  echo $data->some_field;
}

Upvotes: 0

Danish Ali
Danish Ali

Reputation: 2352

Try this

CodeIgniter gives you access to a Query Builder class. This pattern allows information to be retrieved, inserted, and updated in your database with minimal scripting. In some cases, only one or two lines of code are necessary to perform a database action. CodeIgniter does not require that each database table be its own class file. It instead provides a more simplified interface.

public function get_records_all($st_date,$end_date){  
 $this->db->where('added_date >=', $st_date);
 $this->db->where('added_date <=', $end_date);
 $this->db->order_by('added_date', 'DESC');
 return $this->get('crm_listings')->result();
}

For more use this link CI Query Builder CLass

Upvotes: 1

Related Questions