将搜索结果分配给变量 - PHP Fulltext Search Boolean

时间:2011-12-15 07:33:58

标签: php mysql full-text-search search-engine

我使用PHP / MySQL在布尔模式下创建了全文搜索。它运行完美,相关性排名和索引分配给相关的数据库字段。该数据库包含两个表:

业务 - >姓名,描述,联系方式,地址,序列号

* search_terms * - >术语,查询时间,日期_搜索,结果。

然后,我想获取所有搜索结果并将其分配给变量 $ results )。此 $ result 将与terms,querytime和date_searched一起存储到search_term表中。

这是我的代码(没有$ result)

function search($term){
    $term = mysql_real_escape_string($term);
    $startTime = microtime(true);
    $query = mysql_query("SELECT *, MATCH (Name) AGAINST ('+$term*' IN BOOLEAN MODE) AS rel1, MATCH (Description) AGAINST ('+$term*' IN BOOLEAN MODE) AS rel2, MATCH (Keywords) AGAINST ('+$term*' IN BOOLEAN MODE) AS rel3 FROM business WHERE MATCH (Name,Description,Keywords) AGAINST ('+$term*' IN BOOLEAN MODE) ORDER BY (rel1*0.60)+(rel2*0.25)+(rel3*0.15) DESC") or die(mysql_error());
    $endTime = microtime(true);
    $queryTime = substr($endTime - $startTime, 0,6);
    if(mysql_num_rows($query) == 0){
        echo "<p>No results found for <i>". $term ."</i></p>";
    }
    else{
        while($row = mysql_fetch_assoc($query)){
            echo "<h4><a href='viewBusiness.php?serial=" . $row['SerialId'] . "'>" . $row['Name'] . "</a></h4>";
            $desc = substr($row['Description'], 0,100);
            $score = $row['rel1'] + $row['rel2'] + $row['rel3'];
            echo "<p>" . $desc .". . .</p>";
        }
        $numOfResult = mysql_num_rows($query);
        echo "<hr/><p><b>" . $numOfResult ." </b>result(s) found within " . $queryTime . " seconds.</p>";
        $ip = $_SERVER['REMOTE_ADDR'];
        $query2 = mysql_query("INSERT INTO search_term(Term, QueryTime, Ip) VALUES('$term', '$queryTime', '$ip')") or die(mysql_error());
    }
}

我是PHP的新手,这是我的第一个应用程序。非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您可以像这样创建$result到DB:

/* Your code before the cycle... */

$result = array(); /* The array where to store results */
while($row = mysql_fetch_assoc($query)) {
    /* Your code for printing, just as posted... */
    $result[] = $row; /* Store the result row in the array */
}

/* The rest of your code, before second query... */

/* Serialize the result data and save it to database */
$result_serialized = mysql_real_escape_string(serialize($result));
$query2 = mysql_query("
    INSERT INTO search_term(Term, QueryTime, Ip, result) 
    VALUES('$term', '$queryTime', '$ip', '$result_serialized')
") or die(mysql_error());

但请注意:$result(以及$result_serialized)可能非常大,具体取决于结果类型和数量。一定要搞定。 result数据库表中的search_term字段必须是TEXT或更大的字符串数据类型列。

了解 serialize() unserialize()