【问题标题】:search string form multiple column in database table在数据库表中搜索字符串形式的多列
【发布时间】:2012-10-02 06:00:47
【问题描述】:

在我的代码中,我想通过名字、姓氏和电子邮件字段搜索朋友。 现在我想匹配数据库表字段名称中的确切字符串。我还想显示该字段。我还想获取搜索数据的 id,所以之后我将显示关于该人的完整描述。我该怎么做它。 感谢对我的任何帮助。 我试试看。

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

【问题讨论】:

    标签: php mysql database string


    【解决方案1】:

    您正在寻找:

    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']);
    

    Anso 请注意 mysql_* 系列函数正在弃用过程中,你应该看看 PDO 或 mysqli。

    编辑:

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

    【讨论】:

    • 好的兄弟,它很好,但我如何显示这些字段以及如何识别哪些字段与数据库匹配。
    • 我正在使用这种类型的显示器是它给我错误。请检查它
    • $resultsearch=mysql_query($searchquery); while($searchdata=mysql_fetch_array($resultsearch)) {?>
    • 你的错误在这里:<?php } } ?>:删除一个大括号},你只打开了一个大括号while(){,没有更多。
    • 它是.. 这不像准备好的语句那样安全,但很好。
    【解决方案2】:

    查询应该是这样的

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

    如果您想在这 3 列(名字、姓氏、电子邮件)中进行搜索。

    【讨论】:

      【解决方案3】:

      更改您的查询以获取您想要显示的所有必要信息,并根据该术语检查您的 where 语句。像这样:

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

      【讨论】:

        【解决方案4】:
        select firstname,lastname,email from account where concat_ws(' ',firstname,lastname,email) LIKE %$term%"
        

        将所有三个字段视为单个字段,结果会更快

        【讨论】:

        • fistname barjo lastname hnick, 找 john 会匹配吗?如果那真的更快,为什么不实际使用,也许使用 concat_ws 。我会测试一下谢谢你的提示。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-21
        • 2021-01-22
        • 1970-01-01
        • 2018-09-26
        • 1970-01-01
        相关资源
        最近更新 更多