简体   繁体   English

PHP、MySQL:进行更好的搜索?

[英]PHP, MySQL: Making a better search?

I've made a search box feature that allows me to type in a word and then it finds any matches of the word in my database.我制作了一个搜索框功能,允许我输入一个单词,然后它会在我的数据库中找到该单词的任何匹配项。 However, it only finds EXACT matches.但是,它只能找到 EXACT 匹配项。 I'm looking for suggestions on how to make the search better.我正在寻找有关如何使搜索更好的建议。

The code below is what i currently use for searching the databases for users that might be matches for the user searching.下面的代码是我目前用于在数据库中搜索可能与用户搜索匹配的用户的代码。

    $search_keys = array('fname', 'lname', 'email' );

    foreach ( $search_keys as $key )
    {
        $result = mysql_query( "SELECT id FROM users WHERE " . $key . " LIKE " . "\"{$str}\"" ) or die(mysql_error());

        while ( $row = mysql_fetch_array( $result ) )
        {

            // Get the User
            $tmp_user = new User();
            $tmp_user->getUserById( $row['id'] );

            // Add User to list of potential candidates
            array_push($users, $tmp_user);
        }
    }

I see two points where you can improve your code fragment.我看到两点可以改进代码片段。 But first of all take care that $str is properly formatted to be safely used in your SQL query.但首先要注意 $str 的格式正确,以便在 SQL 查询中安全使用。 Otherwise you will run into a problem called SQL Injection .否则你会遇到一个叫做SQL Injection的问题。 I assume that now for your code.我假设现在为您的代码。

  1. Use wildcards with the LIKE SQL function .将通配符与LIKE SQL function 一起使用。
  2. Search across the three fields with one SQL query.使用一个 SQL 查询搜索三个字段。

Please see the example code which contains both suggestions.请参阅包含这两个建议的示例代码。 First the SQL query is build.首先构建 SQL 查询。 There is only need to run one query for all (three) fields instead of one query per field.只需对所有(三个)字段运行一次查询,而不是每个字段一次查询。 That's useful if you extend your search later.如果您稍后扩展搜索,这将非常有用。

/* build SQL query */
$conditions = array();
$search_keys = array('fname', 'lname', 'email' );
foreach ( $search_keys as $key )
{
    $conditions[] = "{$key} LIKE \"%{$str}%\""; # Wildcard (%); [] works like array_push()
}
$query = sprintf('SELECT id FROM users WHERE (%s)', implode(' OR ', $conditions));

/* run SQL query */
$result = mysql_query($query) or die(mysql_error());
while ( $row = mysql_fetch_array( $result ) )
{
    // Get the User
    $tmp_user = new User();
    $tmp_user->getUserById( $row['id'] );

    // Add User to list of potential candidates
    array_push($users, $tmp_user);
}

Well there is always the simplest method of adding the wildcard operator, so if they enter 'Jam' it would be好吧,添加通配符运算符总是有最简单的方法,所以如果他们输入“Jam”,那就是

SELECT id FROM users WHERE fname LIKE '%Jam%'
etc...

EDIT: The point being it would return a match on JAMIE or JAMES or LogJam or (you get the idea), which means they don't need to remember the whole name, just some part of it.编辑:关键是它会在 JAMIE 或 JAMES 或 LogJam 或(你明白了)上返回匹配项,这意味着他们不需要记住整个名称,只需要记住其中的一部分。

I would suggest to use a fulltext database as solr or sphinx for this kind of behaviour.对于这种行为,我建议使用全文数据库作为 solr 或 sphinx。 If you can't or don't want to install it, you should add % to your code.如果您不能或不想安装它,则应在代码中添加 %。 $result = mysql_query( "SELECT id FROM users WHERE ". $key. " LIKE ". "\"%{$str}%\"" ) or die(mysql_error()); $result = mysql_query("SELECT id FROM users WHERE".$key."LIKE"."\"%{$str}%\"") or die(mysql_error());

you should try你应该试试

$result = mysql_query( "SELECT id FROM users WHERE " . $key . " LIKE " . "%" . $str . "%" ) or die(mysql_error());

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

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