根据传入的条件进行模糊查询,这里使用的是CI框架,其他框架模糊查询貌似更简单,不用使用原生SQL,直接使用模型
<?php
class User extends CI_Model {
public function __construct()
{
parent::__construct();
$this->load->database('default');
$this->db->from('user');
}
public function getByAny($search) {
//field1,field2,field3为需要匹配的字段
$query = "SELECT * FROM `user` WHERE CONCAT(field1,field2,field3) LIKE '%".$search."%'";
$result = $this->db->query($query);
return $result->result_array();
}
}
高亮显示主要是使用str_replace()方法将查询的结果进行字符串的替换,再将替换的结果返回到前端。
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Index extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('user');
}
public function search() {
$search = $_GET['search']; //获取前端传过来的查询条件
$rep_str = "<span style='color: orangered'>".$search."</span>"; //设置替换字符串
$result = $this->user->getByAny($search);
foreach ($result as $key => &$value) {
$value['field1'] = str_replace($search,$rep_str,$value['field1']);
$value['field2'] = str_replace($search,$rep_str,$value['field2']);
$value['field3'] = str_replace($search,$rep_str,$value['field3']);
}
return $result;
}
}
如果有错误的地方请指出,一起进步!