Mysql 语句在 CodeIgniter 模型中不起作用 class

Mysql statement not working in CodeIgniter Model class

目前我正在尝试从我的数据中检索特定时间范围内的所有条目。为此,我的模型 class 中有一个方法,其中包含以下语句:

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;
     }

在我的控制器中 class 我使用以下语句来显示输出:

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

但这给了我以下错误:

试试这个

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();
}

更多使用这个linkCI Query Builder CLass

如果你坚持使用 db->query 将你的 get_records_all() 响应更改为 return $response; 那么你可以使用 $data_all 作为对象并像这样

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

您忘记在 $this->db->query($sql) 之后添加 ->result() 喜欢:

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

但是您也可以使用查询生成器,例如

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();
}