PHP搜索结果拆分为页面

时间:2014-11-03 01:04:20

标签: php mysql

我正在为我的网站创建一个搜索引擎,我希望将搜索结果拆分为带导航的页面。这是我的PHP代码

<?php
if (isset($_GET['search'])){
    $search = $_GET['search'];
    $query = "SELECT * FROM search WHERE keywords LIKE '%$search%' OR title LIKE '%$search%' ORDER BY keywords LIMIT 0, 30 ";

    // connect
    mysql_connect("localhost","root","") or die("could not connect");
    mysql_select_db("search") or die("could not find db");

    $query = mysql_query($query);
    $numrrows = mysql_num_rows($query);
    if ($numrrows > 0) {
    echo "$numrrows result found searching for <b>$search </br> ";
        while ($row = mysql_fetch_assoc($query)) {
            $id = $row['id'];
            $title = $row['title'];
            $description = $row['description'];         
            $keywords = $row['keywords'];
            $link = $row['link'];


            echo "<h2><a href='$link'>$title</a></h2>
            $description</b></br>";

            }   
        }
     }
?>  

1 个答案:

答案 0 :(得分:1)

我会使用MySQL OFFSET

步骤1:将页码存储在查询字符串中,例如www.example.com?page=1。这样做无关紧要(无论是表格还是只链接到www.example.com?page=1),但在查询字符串中都有这个数字。

// Assign globals to local variables
if (empty($_GET['page'])) {
  $page = 1;
}
else {
  $page = $_GET['page'];
}

// Pagination
$items = 3; // Number of items per page
$offset = ($page * $items) - $items;

上面的代码采用了页码,并计算了它应该OFFSET的数量。

第2步:编写SQL查询

$query = "SELECT * FROM search WHERE keywords LIKE '%$search%' OR title LIKE '%$search%' ORDER BY keywords LIMIT $items OFFSET $offset";

第3步:分页按钮:转到下一页/上一页可以像

一样简单
<a href="www.example.com?page=<?php echo $page + 1; ?>">Next Page</a>
<?php if ($page != 1) { ?>
<a href="www.example.com?page=<?php echo $page - 1; ?>">Previous Page</a>
<?php } ?>