首页 > 解决方案 > 在 codeigniter 中分页时使用 REGEXP 和 where 条件

问题描述

我有这个从用户那里收到的搜索词,我想返回一些数据,这些数据最终被用来像这样查询 mysql

这就是我查询mysql的方式SELECT * FROM search_data WHERE index_desc REGEXP 'one|two'

public function results()
{
    $searchterm = $this->input->post('searchterm');
    //echo clean($searchterm);
    $myst =  clean($searchterm);
    $myst = trim($myst);
    //Mysql REGEXP
    $search_keywords = str_replace(' ', '|', $myst);
   

   $config = array();
   $config["base_url"] = base_url() . "search/results";
   $config["total_rows"] = $this->Ion_auth_model->record_count();
   $config["per_page"] = 5;
   $config["uri_segment"] = 3;
   $this->pagination->initialize($config);
   $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
   $data["results"] = $this->Ion_auth_model->fetch_data($config["per_page"], $page, $search_keywords);
   $data["links"] = $this->pagination->create_links();
   $this->load->view("results", $data);
}

这是模型函数

    public function fetch_data($limit, $start,$search_keywords) {
       $where_string = 'REGEXP'.$search_keywords;
       $this->db->where('index_desc', $where_string );
       $this->db->limit($limit, $start);
       $query = $this->db->get("search_data");
       if ($query->num_rows() > 0) {
           foreach ($query->result() as $row) {
               $data[] = $row;
           }
           return $data;
       }
       return false;
   }

这是我遇到问题的地方

$where_string = 'REGEXP'.$search_keywords;
$this->db->where('index_desc', $where_string );

因为这是我所期待SELECT * FROM search_data WHERE index_desc REGEXP 'one|two'的,我没有得到我想要的结果。我怎么解决这个问题?。

标签: phpcodeigniter

解决方案


您可以在 CI where() 函数中使用自定义字符串,例如:

$where_string = "index_desc REGEXP '$search_keywords'";
$this->db->where($where_string );

请参阅寻找特定数据,最后一个项目符号 (4)


推荐阅读