搜索功能不适用于某些单词

时间:2015-06-21 09:55:29

标签: php mysql

我遇到的问题是当搜索词“反”它会显示产品但是当基于搜索的词语“抗皱”时没有提到搜索结果。请参考下面的代码和建议我错过了什么。

$search_output = '';

if(isset($_POST['search'])) {
    $searchsql = $_POST['search'];
    $searchsql = preg_replace('#[^a-z 0-9?!@-]#i', '', $searchsql);

    $query = mysql_query("SELECT tb_spa_prd.*, tb_spa_prd_cat.spa_prd_cat FROM tb_spa_prd AS tb_spa_prd INNER JOIN tb_spa_prd_cat ON tb_spa_prd.spa_prd_cat_id = tb_spa_prd_cat.spa_prd_cat_id WHERE spa_prd_cat LIKE '%$searchsql%' or spa_prd_code LIKE '%$searchsql%' or spa_prd_name LIKE '%$searchsql%'")  or die ("Could no search!");
    $count = mysql_num_rows($query);
    if($count == 0) {
        $search_output .= '<tr>
                            <td colspan="9" style="text-align: center">There was no search results!</td>
                            </tr>';
    } else {
        $row_no = 1;
        while($row = mysql_fetch_array($query,MYSQL_ASSOC)) { 
            $spa_prd_id = $row["spa_prd_id"];
            $spa_prd_cat = $row["spa_prd_cat"];
            $spa_prd_code = $row["spa_prd_code"];
            $spa_prd_name = $row["spa_prd_name"];
            $spa_prd_vlm = $row["spa_prd_vlm"];
            $spa_prd_qty = $row["spa_prd_qty"];
            $spa_prd_crt_date = $row["spa_prd_crt_date"];
            $spa_prd_crt_usr = $row["spa_prd_crt_usr"];
            $search_output .= '<tr>
                                    <td>'.$row_no++.'</td>
                                    <td>'.$spa_prd_cat.'</td>
                                    <td>'.$spa_prd_code.'</td>
                                    <td>'.$spa_prd_name.'</td>
                                    <td>'.$spa_prd_vlm.'</td>
                                    <td>'.$spa_prd_qty.'</td>
                                    <td>'.$spa_prd_crt_date.'</td>
                                    <td>'.$spa_prd_crt_usr.'</td>
                            <td><a href=\'edit_spa_prd.php?spa_prd_id='.$spa_prd_id.'\'>Edit</a> | <a href=\'delete_spa_prd.php?spa_prd_id='.$spa_prd_id.'\'>Delete</a></td>
                                </tr>';
        } // close while loop
    }
}

1 个答案:

答案 0 :(得分:0)

您可以尝试为每个搜索字词明确包含LIKE谓词,如下所示:

$searchsql = $_POST['search'];
$terms = explode(" ", $searchsql);
$likecols = array("spa_prd_cat", "spa_prd_code, "spa_prd_name");
$likesql = "";
foreach ($likecols as $likecol) {
    for ($i = 0; $i < count($terms); ++$i) {
        if ($likecol == "spa_prd_cat" && $i == 0) {
            $likesql = "spa_prd_cat LIKE $terms[0]";
        }
        else {
            $likesql .= " OR $likecol LIKE $terms[$i]";
        }
    }
}

$querystr = "SELECT tb_spa_prd.*, tb_spa_prd_cat.spa_prd_cat FROM tb_spa_prd AS tb_spa_prd INNER JOIN tb_spa_prd_cat ON tb_spa_prd.spa_prd_cat_id = tb_spa_prd_cat.spa_prd_cat_id WHERE ";
$querystr .= $likesql;
$query = mysql_query($querystr) or die ("Could no search!");