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 = '';
              $startDate = $this->input->post('startDate');
               $endDate = $this->input->post('endDate');

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

But this gives me the following error:

Mysql statement not working in CodeIgniter Model class


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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;

Method 3

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

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x