简体   繁体   English

PHP搜索引擎无法正常工作?

[英]Php search engine not working?

I'm working on a simple search engine that gets you information but I'm having a problem. 我正在使用一个简单的搜索引擎来获取您的信息,但是我遇到了问题。 You see when I put a space into the search input it doesn't give you the message saying "no key words searched please try again" but when you click the search button without adding anything in the search input it works. 您会看到,当我在搜索输入中添加空格时,并没有显示“没有搜索到关键词,请重试”的消息,但是当您单击搜索按钮而未在搜索输入中添加任何内容时,它会起作用。 How could i fix this to make it work with both? 我该如何解决这个问题以使其与两者同时使用?

Code: 码:

if(!$db) {
    die('sorry we are having some problbems');
}


$searchTerm = mysqli_real_escape_string($db,$_GET['term']);

if ( empty($searchTerm))
{
echo("no key words searched please try again");
}
else
{
$sql = mysqli_query(
    $db,
    sprintf(
        "SELECT * FROM searchengine WHERE name LIKE '%s' LIMIT 0,20",
        '%'. $searchTerm .'%'
    )
);

while($ser = mysqli_fetch_array($sql)) {
    echo "<a href='$ser[pageurl]'>$ser[img]</a>";
}
}

mysqli_close($db);
?>

Use trim() to remove leading and trailing spaces. 使用trim()删除前导和尾随空格。

$searchTerm = trim($searchTerm);

if ($searchTerm == '') {
    echo("no key words searched please try again");
} else {
    ...
}

Check for whitespace in addition to the empty search term. 除空白搜索词外,还要检查空格。 Here I'm using the regular expressions preg_match to find any whitespace characters that could be entered. 在这里,我使用正则表达式preg_match查找可以输入的任何空白字符。

if (empty($searchTerm)||preg_match('!^\s+$!',$searchTerm))
  {
    echo("no key words searched please try again");
  }
else...

Or with preg_match alone 或单独使用preg_match

if (preg_match('!^\s*$!',$searchTerm))
  {
    echo("no key words searched please try again");
  }
else...

Another method you could use is to check the string length using strlen 您可以使用的另一种方法是使用strlen检查字符串长度

if (strlen($searchTerm)<4)
  {
    echo("no key words searched please try again");
  }
else...

试试这个查询,而不是使用sprintf

    "SELECT * FROM searchengine WHERE name LIKE '%$searchsting%' LIMIT 0,20"

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

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