2012-01-13 49 views
2

我想搜索的字段名字和姓氏的关键字加入MySQL的2场,同时

$q1 = strtolower($_GET["q"]); 
$q=str_replace(" ","%",$q1); 
$sql = "select DISTINCT users.*, user_id FROM users WHERE $email_filter 
firstname LIKE '%$q%' OR lastname LIKE '%$q%' ORDER BY lastname"; 
$rsd = mysql_query($sql); 
while($rs = mysql_fetch_array($rsd)) { echo $results } 

这同时搜索是我到目前为止,问题是,如果你使用李四作为一个例子,一旦你键入约翰找到它,能源部它发现它,但李四......没有结果

+2

您需要连接第一和姓领域,并比较*是*您搜索字符串,按[下使用mysql concat()在WHERE子句?](http://stackoverflow.com/questions/303679/using-mysql-concat-in-where-clause) – 2012-01-13 23:56:32

回答

0

喜欢的东西

SELECT * FROM users where CONCAT(firstname, ' ', lastname) like '%$q%' 

或者

SELECT * FROM users where CONCAT_WS(' ', firstname, lastname) like '%$q%' 

如果倒车是可取的,试试这个:

SELECT * FROM users where CONCAT_WS(' ', firstname, lastname) like '%$q%' 
         or CONCAT_WS(' ', lastname, firstname) like '%$q%' 

(也就是说,如果搜索 “AB” 应该回到 “AB” 以及 “BA”)

+0

但是不会找到doe john – kaklon 2012-01-15 21:00:19

+0

它应该*不*返回“John Doe “当查询是”Doe John“时。如果它应该,那么你有一个不同的问题。我错过了那部分。请确认你想要这样,我会尝试。 – MJB 2012-01-15 21:04:33

0

我建议你绑定变量。否则,您将接触到sql注入。

$stmt = $mysqli->prepare("select * from users where firstname like ? AND lastname like ?"); 
$stmt->bind_param('ss', $firstname,$lastname); 
+0

这是一个有用的建议,但与问题无关。 – MJB 2012-01-16 13:16:23

0

你必须拆分您的查询字符串,然后搜索各方面

$query_terms = explode(" ", $q1); 
$conditions = '' 
foreach($query_terms as $term){ 
    $conditions = $conditions.' firstname LIKE "%'.$term.'%" OR lastname LIKE "%'.$term.'%"'; 
} 

$sql = "select DISTINCT users.*, user_id FROM users WHERE $email_filter $conditions ORDER BY lastname";