PHP/MySQL 中的多词搜索

发布于 2024-12-20 21:49:43 字数 2879 浏览 1 评论 0原文

我正在努力创建一个搜索多个单词的搜索。我的第一次尝试没有产生任何结果,如下:

  require_once('database_conn.php');
  if($_POST){
  $explodedSearch = explode (" ", $_POST['quickSearch']);


  foreach($explodedSearch as $search){
  $query = "SELECT * 
            FROM jobseeker 
            WHERE forename like '%$search%' or surname like '%$search%' 
            ORDER BY userID 
            LIMIT 5";
  $result = mysql_query($query);
}

while($userData=mysql_fetch_array($result)){
    $forename=$userData['forename'];
    $surname=$userData['surname'];
    $profPic=$userData['profilePicture'];
    $location=$userData['location'];

    echo "<div class=\"result\">
    <img class=\"quickImage\" src=\"" . $profPic. "\" width=\"45\" height=\"45\"/>
    <p class=\"quickName\">" . $forename . " " . $surname . "</p>
    <p class=\"quickLocation\"> " . $location . "</p>
    </div>";

}
}  

我还尝试了以下方法,产生了结果,但正如你可以想象的,我输入的每个单词都得到了重复的结果:

if($_POST){
$explodedSearch = explode (" ", $_POST['quickSearch']);


foreach($explodedSearch as $search){
$query = "SELECT * 
          FROM jobseeker 
          WHERE forename like '%$search%' or surname like '%$search%' 
          ORDER BY userID 
          LIMIT 5";
$result .= mysql_query($query);


while($userData=mysql_fetch_array($result)){
    $forename=$userData['forename'];
    $surname=$userData['surname'];
    $profPic=$userData['profilePicture'];
    $location=$userData['location'];

    echo "<div class=\"result\">
    <img class=\"quickImage\" src=\"" . $profPic. "\" width=\"45\" height=\"45\"/>
    <p class=\"quickName\">" . $forename . " " . $surname . "</p>
    <p class=\"quickLocation\"> " . $location . "</p>
    </div>";
}
}
}

我几乎不知道如何为了继续进行此工作,我们将不胜感激任何帮助。

编辑:

if($_POST){
$quickSearch = $_POST['quickSearch'];
$explodedSearch = explode (" ", trim($quickSearch));


$queryArray = array();

foreach($explodedSearch as $search){
$term = mysql_real_escape_string($search);
$queryArray[] = "forename like '%" . $term .  "%' surname like '%" . $term . "%'";
}

$implodedSearch = implode(' or ', $queryArray);

$query="SELECT *
        FROM jobseeker
        WHERE ($implodedSearch)
        ORDER BY userID
        LIMIT 5";

$result = mysql_query($query);

while($userData=mysql_fetch_array($result, MYSQL_ASSOC)){
    $forename=$userData['forename'];
    $surname=$userData['surname'];
    $profPic=$userData['profilePicture'];
    $location=$userData['location'];


    echo "<div class=\"result\">
    <img class=\"quickImage\" src=\"" . $profPic. "\" width=\"45\" height=\"45\"/>
    <p class=\"quickName\">" . $forename . " " . $surname . "</p>
    <p class=\"quickLocation\"> " . $location . "</p>
    </div>";

}
}

I'm struggling to create a search that searches for multiple words. My first attempt yielded no results whatsoever and is as follows:

  require_once('database_conn.php');
  if($_POST){
  $explodedSearch = explode (" ", $_POST['quickSearch']);


  foreach($explodedSearch as $search){
  $query = "SELECT * 
            FROM jobseeker 
            WHERE forename like '%$search%' or surname like '%$search%' 
            ORDER BY userID 
            LIMIT 5";
  $result = mysql_query($query);
}

while($userData=mysql_fetch_array($result)){
    $forename=$userData['forename'];
    $surname=$userData['surname'];
    $profPic=$userData['profilePicture'];
    $location=$userData['location'];

    echo "<div class=\"result\">
    <img class=\"quickImage\" src=\"" . $profPic. "\" width=\"45\" height=\"45\"/>
    <p class=\"quickName\">" . $forename . " " . $surname . "</p>
    <p class=\"quickLocation\"> " . $location . "</p>
    </div>";

}
}  

I also tried the following, which yielded results, but as you can imagine, I was getting duplicate results for every word I entered:

if($_POST){
$explodedSearch = explode (" ", $_POST['quickSearch']);


foreach($explodedSearch as $search){
$query = "SELECT * 
          FROM jobseeker 
          WHERE forename like '%$search%' or surname like '%$search%' 
          ORDER BY userID 
          LIMIT 5";
$result .= mysql_query($query);


while($userData=mysql_fetch_array($result)){
    $forename=$userData['forename'];
    $surname=$userData['surname'];
    $profPic=$userData['profilePicture'];
    $location=$userData['location'];

    echo "<div class=\"result\">
    <img class=\"quickImage\" src=\"" . $profPic. "\" width=\"45\" height=\"45\"/>
    <p class=\"quickName\">" . $forename . " " . $surname . "</p>
    <p class=\"quickLocation\"> " . $location . "</p>
    </div>";
}
}
}

I'm pretty much at a loss as to how to proceed with this, any help would be greatly appreciated.

EDIT:

if($_POST){
$quickSearch = $_POST['quickSearch'];
$explodedSearch = explode (" ", trim($quickSearch));


$queryArray = array();

foreach($explodedSearch as $search){
$term = mysql_real_escape_string($search);
$queryArray[] = "forename like '%" . $term .  "%' surname like '%" . $term . "%'";
}

$implodedSearch = implode(' or ', $queryArray);

$query="SELECT *
        FROM jobseeker
        WHERE ($implodedSearch)
        ORDER BY userID
        LIMIT 5";

$result = mysql_query($query);

while($userData=mysql_fetch_array($result, MYSQL_ASSOC)){
    $forename=$userData['forename'];
    $surname=$userData['surname'];
    $profPic=$userData['profilePicture'];
    $location=$userData['location'];


    echo "<div class=\"result\">
    <img class=\"quickImage\" src=\"" . $profPic. "\" width=\"45\" height=\"45\"/>
    <p class=\"quickName\">" . $forename . " " . $surname . "</p>
    <p class=\"quickLocation\"> " . $location . "</p>
    </div>";

}
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

聚集的泪 2024-12-27 21:49:43

我一直在研究同一主题(使用关键字搜索)一段时间,我是这样做的:

$words = $_POST['keywords'];
if(empty($words)){
    //redirect somewhere else!
}
$parts = explode(" ",trim($words));
$clauses=array();
foreach ($parts as $part){
    //function_description in my case ,  replace it with whatever u want in ur table
    $clauses[]="function_description LIKE '%" . mysql_real_escape_string($part) . "%'";
}
$clause=implode(' OR ' ,$clauses);
//select your condition and add "AND ($clauses)" .
$sql="SELECT * 
      FROM functions 
      WHERE
      user_name='{$user_name}'
      AND ($clause) ";
$results=mysql_query($sql,$connection);
 if(!$results){
    redirect("errors/error_db.html");
 }
 else if($results){
 $rows = array();
<?php 
 while($rows = mysql_fetch_array($results, MYSQL_ASSOC))
{
   // echo whatever u want !
}
?>

-现在这是我尝试使用全文搜索运行它时的样子:
但你应该将表类型设置为“MyISAM”

<?php
$words = mysql_real_escape_string($_POST['function_keywords']);
if(empty($words)){
    redirect("welcome.php?error=search_empty");
}
//if the columns(results)>1/2(columns) => it will return nothing!(use "NATURAL LANGUAGE"="BOOLEAN")
$sql="SELECT * FROM functions
     WHERE MATCH (function_description)
     AGAINST ('{$words}' IN NATURAL LANGUAGE MODE)";
$results=mysql_query($sql,$connection);
 if(!$results){
    redirect("errors/error_db.html");
 }
 else if($results){
$rows = array();
while($rows = mysql_fetch_array($results, MYSQL_ASSOC))
{
     // echo 
}
}
?>

I've been working on the same subject (search with keywords) for a while and this how i did it :

$words = $_POST['keywords'];
if(empty($words)){
    //redirect somewhere else!
}
$parts = explode(" ",trim($words));
$clauses=array();
foreach ($parts as $part){
    //function_description in my case ,  replace it with whatever u want in ur table
    $clauses[]="function_description LIKE '%" . mysql_real_escape_string($part) . "%'";
}
$clause=implode(' OR ' ,$clauses);
//select your condition and add "AND ($clauses)" .
$sql="SELECT * 
      FROM functions 
      WHERE
      user_name='{$user_name}'
      AND ($clause) ";
$results=mysql_query($sql,$connection);
 if(!$results){
    redirect("errors/error_db.html");
 }
 else if($results){
 $rows = array();
<?php 
 while($rows = mysql_fetch_array($results, MYSQL_ASSOC))
{
   // echo whatever u want !
}
?>

-- Now this is how it look when i tried to run it with FULLTEXT search :
But you should set the table type as "MyISAM"

<?php
$words = mysql_real_escape_string($_POST['function_keywords']);
if(empty($words)){
    redirect("welcome.php?error=search_empty");
}
//if the columns(results)>1/2(columns) => it will return nothing!(use "NATURAL LANGUAGE"="BOOLEAN")
$sql="SELECT * FROM functions
     WHERE MATCH (function_description)
     AGAINST ('{$words}' IN NATURAL LANGUAGE MODE)";
$results=mysql_query($sql,$connection);
 if(!$results){
    redirect("errors/error_db.html");
 }
 else if($results){
$rows = array();
while($rows = mysql_fetch_array($results, MYSQL_ASSOC))
{
     // echo 
}
}
?>
脸赞 2024-12-27 21:49:43

也许您正在寻找的是 MySQL 全文搜索。

对于您的示例,您可以执行以下操作:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $search = $_POST['quickSearch'];
    // Todo: escape $search
    $sql = "
        SELECT
            *,
            MATCH (`forename`)
            AGAINST ('{$search}' IN NATURAL LANGUAGE MODE) AS `score`
        FROM `jobseeker`
        WHERE
            MATCH (`forename`)
            AGAINST ('{$search}' IN NATURAL LANGUAGE MODE)";
    // Todo: execute query and gather results
}

请注意,您需要将 FULLTEXT 索引添加到 forename 列。

Perhaps what you are looking for is a MySQL full-text search.

For your example, you could do something like:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $search = $_POST['quickSearch'];
    // Todo: escape $search
    $sql = "
        SELECT
            *,
            MATCH (`forename`)
            AGAINST ('{$search}' IN NATURAL LANGUAGE MODE) AS `score`
        FROM `jobseeker`
        WHERE
            MATCH (`forename`)
            AGAINST ('{$search}' IN NATURAL LANGUAGE MODE)";
    // Todo: execute query and gather results
}

Note that you will need to add a FULLTEXT index to the column forename.

花海 2024-12-27 21:49:43

如果您必须的话,请查看 MySQL 全文搜索使用MySQL。否则,请查看 SOLR,它是一个全文搜索引擎。您可以结合使用 MySQL 和 SOLR 为您的应用程序提供企业级搜索功能。

Take a look at MySQL fulltext searches, if you must use MySQL. Otherwise take a look at SOLR, which is a fulltext search engine. You can use MySQL and SOLR in combination to provide enterprise level search capabilities for your apps.

心碎无痕… 2024-12-27 21:49:43

这就是我所做的

if (isset($_POST['search'])){
$words = mysql_real_escape_string($_POST['searchfield']);   
$arraySearch = explode(" ", trim($words));       
$countSearch = count($arraySearch);
$a = 0;
$query = "SELECT * FROM parts WHERE ";
$quote = "'";
while ($a < $countSearch)
{
  $query = $query."description LIKE $quote%$arraySearch[$a]%$quote ";
  $a++;
  if ($a < $countSearch)
  {
    $query = $query." AND ";
    }   
  }
    $result=mysql_query($query) or die(error);

//你可以把它留在这里,简短而甜蜜,但我添加了一些额外的代码,如果它没有出现任何结果,那么它会搜索其中一个单词而不是两个单词//

$num = mysql_num_rows($result);
if ($num == 0){
 $a = 0;
 $query = "SELECT * FROM parts WHERE ";
while ($a < $countSearch)
{
  $query = $query."description LIKE $quote%$arraySearch[$a]%$quote ";
  $a++;
  if ($a < $countSearch)
  {
    $query = $query." OR ";
    $msg = "No exact match for: $words. Maybe this is what you're looking for though? If not please try again.";
    }

  }
  }
  $result=mysql_query($query) or die($query);
  if (mysql_num_rows($result) == 0){
    $msg = "No results, please try another search";
    }

}

here's what i did

if (isset($_POST['search'])){
$words = mysql_real_escape_string($_POST['searchfield']);   
$arraySearch = explode(" ", trim($words));       
$countSearch = count($arraySearch);
$a = 0;
$query = "SELECT * FROM parts WHERE ";
$quote = "'";
while ($a < $countSearch)
{
  $query = $query."description LIKE $quote%$arraySearch[$a]%$quote ";
  $a++;
  if ($a < $countSearch)
  {
    $query = $query." AND ";
    }   
  }
    $result=mysql_query($query) or die(error);

//you could just leave it here, short and sweet but i added some extra code for if it doesnt turn up any results then it searches for either word rather than boths words//

$num = mysql_num_rows($result);
if ($num == 0){
 $a = 0;
 $query = "SELECT * FROM parts WHERE ";
while ($a < $countSearch)
{
  $query = $query."description LIKE $quote%$arraySearch[$a]%$quote ";
  $a++;
  if ($a < $countSearch)
  {
    $query = $query." OR ";
    $msg = "No exact match for: $words. Maybe this is what you're looking for though? If not please try again.";
    }

  }
  }
  $result=mysql_query($query) or die($query);
  if (mysql_num_rows($result) == 0){
    $msg = "No results, please try another search";
    }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文