当我搜索单词“apple”时,脚本按以下顺序显示结果:
(1)appletree (2)juiceapple (3)苹果
但我想按以下顺序重新排序搜索结果:
(1)苹果 (2)appletree (3)juiceapple
正如您所看到的,上面的顺序正是我想要的结果显示根据搜索的术语“苹果”
//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>
}
}
}
}
答案 0 :(得分:2)
按asc
使用订单$ construct =&#34; SELECT * FROM word WHERE $ construct ORDER BY [Field name from you ascend your search] ASC&#34 ;;
答案 1 :(得分:2)
尝试
ORDER BY关键字Asc
获得所需的结果
答案 2 :(得分:1)
使用ORDER BY keywords ASC
它会按预期为您提供适当的结果。
答案 3 :(得分:1)
如果你对长度的关注意味着尝试LENGTH()
$construct = "SELECT * FROM word WHERE $construct order by LENGTH(`keywords`)
答案 4 :(得分:1)
我假设您每行都有多个关键字。您将获得所有这些结果,因为您正在搜索包含单词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:分隔符可以是任何字符串或字符,它不必是空格