我试图限制像Google这样的每个网页上的搜索结果数量。我也使用SQL数据库来组织我的关键字和一切。这是我的代码
<?php
$q = $_GET['q'];
$terms = explode(" ", $q);
//connect
mysql_connect("localhost", "root", "") or die ("Could Not Connect");
mysql_select_db("search") or die ("Could Not Connect To database");
$query = "SELECT * FROM search ";
$i=1;
foreach ($terms as $each){
if ($i == 1) {
$query .= "WHERE ";
$query .= "keywords LIKE '" . mysql_real_escape_string("%" . $each . "%") . "' ";
} else {
$query .= "OR keywords LIKE '" . mysql_real_escape_string("%" . $each . "%") . "' ";
}
$i++;
}
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if ($numrows > 0)
{
while($row = mysql_fetch_assoc($query))
{
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
echo "<h3><a href='$link'>$title</a></h3><h4>$link</h4>$description<br /><br />";
}
} else {
echo "<b>No Results Found</b><br><br>Suggestions:<br>
Make sure all words are spelled correctly.<br>
Try different keywords.<br>
Try more general keywords.";
}
//disconnect
mysql_close();
&GT;
答案 0 :(得分:1)
在foreach ($terms as $each){}
之后,您需要在查询中添加ORDER BY
和LIMIT
,如下所示:
$query .= "ORDER BY keywords LIMIT 0, 10";
这将为您提供前10个结果。根据需要更改LIMIT变量。第一个数字是偏移量(基于零,又名第一个结果是0,第六个结果是5),第二个数字是要返回的行数。
ORDER BY有助于获得一致的结果。你不需要它,但有时结果可能很奇怪。
如果需要,请参阅this question以获取更多信息。