本文介绍了适用于mySQL数据库的PHP搜索脚本,仅工作3个字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对MySQL数据库进行php搜索.下面的代码很有趣,当我只输入3个字母时,它会很好地检测到.例如,如果我输入的是"ome",它的产品名称为"deepbluehealth omega",如果输入的是"ega",则我的产品名称为"deepbluehealth omega".输入'omega'不会显示任何结果,如果我输入'deepbluehealth'也不会出现问题.

I am trying to do a php search into mySQL database. the following code works funny, it detect very well when I only entered 3 letter..eg i have a product name 'deepbluehealth omega' if i type 'ome' it picked up, if i type 'ega' it picked up, if i type 'omega' no result shown, also if i type 'deepbluehealth' it pick up no problem.

<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$search_output = "";
if(isset($_POST['searchquery']) && $_POST['searchquery'] != ""){
    $searchquery = $_POST['searchquery'];
    if($_POST['filter1'] == "Whole Site"){
    $sqlCommand = "(SELECT id, product_name FROM products WHERE product_name LIKE '%$searchquery%' OR details LIKE '%$searchquery%') ";
    } 
    require_once("storescripts/connect_to_mysqli.php");
    $query = mysqli_query($myConnection,$sqlCommand) or die(mysqli_error($myConnection));
    $count = mysqli_num_rows($query);
    if($count > 1){
        $search_output .= "<hr />$count results for <strong>$searchquery</strong><hr />$sqlCommand<hr />";
        while($row = mysqli_fetch_array($query)){
                $id=$row["id"];
            $product_name = $row["product_name"];
                    $details= $row["details"];
                $category=$row["category"];
                $subcategory=$row["subcategory"];
            $search_output .= "ID: $id <br/> Name: $product_name -<br/>$details<br />$category<br/>$subcategory<br/>
<a href='product.php?id=$id'>link</a><br/>

";
        } // close while
    } else {
        $search_output = "<hr />0 results for <strong>$searchquery</strong><hr />$sqlCommand";
    }
}
?>
<html>
<head>
</head>
<body>
<h2>Search the Exercise Tables</h2>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Search For: 
  <input name="searchquery" type="text" size="44" maxlength="88"> 
Within: 
<select name="filter1">
<option value="Whole Site">Whole Site</option>

</select>
<input name="myBtn" type="submit">
<br />
</form>
<div>
<?php echo $search_output; ?>
</div>
</body>
</html>

推荐答案

这是您的问题:

if($count > 1){

这必须是:

if($count > 0){

考虑只有一个结果的情况.可能这是唯一匹配"omega"的产品,但在其他所有情况下,碰巧都匹配了另一个产品.

To account for the case where there is exactly one result. Probably this is the only product that matched "omega" but in every other case, another product happened to match.

这篇关于适用于mySQL数据库的PHP搜索脚本,仅工作3个字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 11:58