1

当我搜索单词“apple”时,脚本按以下顺序显示结果:

(1) 苹果树 (2) 果汁苹果 (3) 苹果

但我想按以下顺序重新排序搜索结果:

(1) 苹果 (2) 苹果树 (3) 果汁苹果

正如你所看到的,上面的顺序正是我想要的,结果根据搜索词“苹果”显示

//get date
$button = $_GET['submit'];
$search = $_GET['search'];

if (!$button)
   echo "Please fill out the form";
else
{
    if (strlen($search)<=2)
   echo "The item you searched for was to small";
    else
   {
     echo "You searched for <b>$search</b> <hr size='1'>";

     //connect to database

     mysql_connect('localhost','wnumber','passowrd');
     mysql_select_db('wnumber');


 //explode search term
           $search_exploded = explode(" ",$search);
           foreach($search_exploded as $search_each)
{
    $str = mysql_real_escape_string(substr($search_each, 0, 4));
    //construct query
    $x++;
    if ($x==1) $construct .= "keywords LIKE '$str%'";
    else       $construct .= " OR keywords LIKE '$str%'";
}




     //echo out construct
    $construct = "SELECT * FROM word WHERE $construct";
    $run = mysql_query($construct);
     $foundnum = mysql_num_rows($run);

     if ($foundnum==0)
        echo "No results found.";
     else
     {

       echo "$foundnum results found.<p><hr size='1'>";

       while ($runrows = mysql_fetch_assoc($run))
       {


        //get data
       $meaning = $runrows['meaning'];
       $keywords = $runrows['keywords'];

        echo "<b>$keywords</b><br>
       <b>$meaning</b><br>

       }

     }



    }
}
4

5 回答 5

2

按 asc 使用顺序

$construct = "SELECT * FROM word WHERE $construct ORDER BY [你想提升搜索的字段名称] ASC";

于 2012-12-18T07:30:51.523 回答
2

尝试

ORDER BY 关键字 Asc

为了得到想要的结果

于 2012-12-18T07:40:17.333 回答
1

使用ORDER BY keywords ASC它将按预期为您提供适当的结果。

于 2012-12-18T07:34:34.263 回答
1

如果您对长度的关注意味着尝试,除了升序之外LENGTH()

$construct = "SELECT * FROM word WHERE $construct order by LENGTH(`keywords`)
于 2012-12-18T07:38:53.457 回答
1

我假设每一行都有多个关键字。您得到所有​​这些结果是因为您正在搜索包含 word 的任何单词apple

要首先获得准确的结果,然后只获得包含该单词的结果,请执行以下操作:

  1. 搜索与单词“apple”完全匹配的结果
  2. 搜索包含单词“apple”的任何结果

由于每一行都有多个关键字,因此不能使用=运算符。但是您必须separator在表格中使用一些来将关键字彼此分开。让我们假设它的“ ”(空白)。

因此,例如,如果您的表和列“关键字”看起来像这样

| id | name  | keywords |
| 1  | apple | apple fruit sweet |

您可以搜索这样的结果:

SELECT * FROM table t1
WHERE
 keywords LIKE "% $keyword %" /* Notice whitespaces around the variable */
 OR
 keywords LIKE "$keyword %" /* This is for keywords that arent separated from left */
 OR
 keywords LIKE "% $keyword" /* This is for keywords that arent separated from right */

UNION DISTINCT /* Distinct is there because we want to show every result just once */

SELECT * FROM table t1
WHERE
 keywords LIKE "%$keyword%"

PS:分隔符可以是任何字符串或字符,不一定是空格

于 2012-12-18T07:52:05.813 回答