查询使用like语句但不使用全文mysql索引

时间:2014-04-13 21:48:27

标签: php mysql sql

我正在尝试创建一个搜索引擎来启用用户数据搜索。我尝试在sql查询中使用,但它的工作原理。现在我想使用mysql全文索引,如下面的代码,但它在搜索时不显示任何数据。我的表创建为myislam,启用了全文索引。下面是代码

<?php
include('searchajax_db.php');
if($_POST) {
    $q=mysql_real_escape_string($_POST['search']);
    $sql_res=mysql_query("select * from articles WHERE MATCH(title,body) AGAINST ('$q') 
        order BY MATCH(title,body) AGAINST ('$q')");

    //$sql_res=mysql_query("select id,title,body from articles where title like '%$q%' or body like '%$q%' ");
    //
    if($sql_res === FALSE) {
        die(mysql_error()); // TODO: better error handling
    }

    while($row=mysql_fetch_array($sql_res)) {
        $ut=$row['title'];
        $ub=$row['body'];
        $b_ust=''.$q.'';
        $b_emb=''.$q.'';
        $final_u = str_ireplace($q, $b_ust, $ut);
        $final_e = str_ireplace($q, $b_emb, $ub);
?>
<div class="show" align="left">
<?php echo '<a  data-role="button" data-transition="fade" data-icon="arrow-r" data-iconpos="right" data-inline="true" href=profile.php?id='.htmlentities($row["id"], ENT_QUOTES, "UTF-8") .' title="Click to Find ">'.'<font color=orange></font>'.'' 
?>
<?php echo '<font color=greenyellow>' ?>
<span class="name"><?php echo htmlentities($final_u, ENT_QUOTES, "UTF-8"); ?></span>&nbsp;<br/>
<?php echo htmlentities($final_e, ENT_QUOTES, "UTF-8"); ?><br/>
<?php echo '</font>' ?>
</div>
<?php }} ?>

1 个答案:

答案 0 :(得分:0)

您无需在任何地方使用MATCH。 WHERE条件是您确定从表中检索哪些行的位置。在SELECT之后,您可以选择显示这些行中的哪些列。 ORDER BY确定行按哪个列和方向排序。

这个例子可能就足够了:

SELECT title, body FROM articles WHERE MATCH(title,body) AGAINST ('$q') ORDER BY title ASC

我还会注意到你应该使用PDO或MySQLi的预处理语句,因为它比使用mysql_real_escape_string更好的保护。