Codeigniter用空格搜索

时间:2014-04-05 03:33:03

标签: mysql codeigniter sql-like

我有一个搜索功能,可以搜索数据库中的用户。

模型看起来像这样

public function search_user_details($conditions){
$search = $conditions["search"];


$this->db->like('username', $search);
$this->db->or_like('first_name', $search);
$this->db->or_like('last_name', $search);
$this->db->from($this->user_table);
$this->db->select("id, first_name, last_name, username, password, email, bio, country,     avatar, cover, notes_check, verified, private, POST_SCORE, COMMENT_SCORE");
$this->db->limit(200);
$query= $this->db->get();

results = $query->result_array();
return $results;
}

示例,用户具有以下详细信息:first_name = Fran,last_name = Allison,username = fran。

如果我搜索其中任何一个,她的详细信息将被退回:fran,allison。 如果我搜索:'Fran Allison'一起没有任何回复。 例如$ conditions [“search”] =“Fran Allsion”

有什么想法吗?

由于

1 个答案:

答案 0 :(得分:0)

public function search_user_details($conditions) {
     $search = $conditions["search"];

     $first = $search;
     $last = $search;

     // If the search contains a space, separate the two words.
     if(preg_match('/\s/', $search))
     {
          $name = explode(" ", $search);
          $first = $name[0];
          $last = $name[1];
     }

     $this->db->like('username', $search);
     $this->db->or_like('first_name', $first);
     $this->db->or_like('last_name', $last);

     // This is in case they search Lastname first. 
     $this->db->or_like('first_name', $last);
     $this->db->or_like('last_name', $first);

     $this->db->from($this->user_table);
     $this->db->select("id, first_name, last_name, username, password, email, bio, country,     avatar,      cover, notes_check, verified, private, POST_SCORE, COMMENT_SCORE");
     $this->db->limit(200);
     $query= $this->db->get();

     results = $query->result_array();
     return $results;
}