简体   繁体   English

mysql / sql用一个关键字字符串搜索名字和姓氏

[英]mysql/sql search for first name and last name with one keyword string

I have the following fields: firstname and lastname keyword is $keyword if someone searches for: John Doe I want it to be able to return results. 我有以下字段:如果有人搜索,firstname和lastname关键字是$keyword :John Doe我希望它能够返回结果。 now it returns results if its john, or if its doe. 现在它返回结果,如果它的约翰,或它的母鹿。 here is the code: 这是代码:

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

any help would be greatly appreciated thank you! 任何帮助将不胜感激,谢谢!

You want cases where the first name and the last name match your parameters, not the first name or the last name so it should be firstname LIKE '%$q%' AND lastname LIKE '%$q%' 您需要的情况下,名字和姓氏与您的参数匹配,而不是名字或姓氏,因此它应该是名字LIKE'%$ q%'和姓氏LIKE'%$ q%'

Keep in mind that since you are using LIKE, if the name is John Doe, Johnnie Doe, John Does, Johnnie Does these will all be returned along with any other records where the first name contains John and the last name contains Doe. 请记住,由于您使用的是LIKE,因此,如果名称是John Doe,Johnnie Doe,JohnDoes,JohnnieDoes,这些将与名字包含John且姓氏包含Doe的所有其他记录一起返回。

If the user provides a response like "John Doe" this should trim any extra white space, break the provided names into values and query on them based on your provided code: 如果用户提供诸如“ John Doe”之类的响应,则应修剪所有多余的空白,将提供的名称拆分为值,然后根据提供的代码对它们进行查询:

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

hope it helps 希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM