2012-10-02 147 views
1

在我的代码中,我想通过名字,姓氏和电子邮件字段来搜索朋友。 现在我想匹配从数据库表字段name.also确切的字符串,我想显示fields.also我想获得搜索数据的ID所以然后我会显示关于该人的完整描述后,我可以做到这一点。 感谢任何帮助。 我尝试过。在数据库表中搜索字符串表格多列

$term=$_POST['find']; 
$searchquery=mysql_query("select firstname,lastname,email from account where output LIKE %$term%"); 

回答

2

您正在寻找:

SELECT id, firstname, lastname, email 
FROM account 
WHERE firstname LIKE %$term% 
OR lastname LIKE %$term% 
OR email LIKE %$term% 
LIMIT 20 

请注意,你的方法是潜在的危险,你要保护你的$term变量:

$term = mysql_real_escape_string($_POST['find']); 

安苏注意mysql_ *系列功能正在弃用的过程,你应该看看PDO或mysqli。

编辑:

增加了一个限制,因为我不认为你要恢复所有数据库表,如果$term包含任何内容。

+0

好兄弟的不错,但我怎么可以显示的字段,以及如何确定哪些字段是匹配的数据库。 – pratik

+0

我使用这种类型显示它是否给我error.pls检查它 – pratik

+0

$ resultsearch = mysql_query($ searchquery); \t而($ searchdata = mysql_fetch_array($ resultsearch)) \t {?> <表边界= “0” CELLPADDING = “0” CELLSPACING = “0” ALIGN = “中心”> \t ​​ <? php \t \t \t echo $ searchdata ['firstname']; \t \t \t echo $ searchdata ['lastname']; \t \t \t echo $ searchdata ['email']; \t \t \t?> \t \t \t \t <?PHP} } ?> – pratik

1

查询应该是这样的

$searchquery=mysql_query("select id,firstname,lastname,email from account where firstname LIKE '%$term%' OR lastname LIKE '%$term%' OR email LIKE '%$term%'"); 

,如果你想在这两种3列(名字,姓氏,电子邮件)进行查询。

1

更改您的查询以获取您想要显示的所有需要​​的信息,并检查您对该字词的所在位置。就像这样:

select id, firstname, lastname, email /*, ... other fields */ from account where firstname LIKE '%$term%' OR lastname LIKE '%$term%' OR email LIKE '%$term%' 
1
select firstname,lastname,email from account where concat_ws(' ',firstname,lastname,email) LIKE %$term%" 

会像对待单一领域,因此这三个领域将更快

+1

fistname barjo lastname hnick,寻找约翰会匹配?如果这真的很快,为什么不实际,也许使用concat_ws。我会测试它,谢谢你的提示。 –

+0

是的... concat_ws与分隔符应该工作的空白 – hangman