我无法在搜索结果页面上进行分页处理



我创建了一个搜索网站,人们可以通过提交关键字来搜索项目,结果将显示在结果页面上。我一直在尝试使搜索结果页面包含分页,因为我只想每页显示 10 个结果。我想知道是否有人知道如何做到这一点,因为我遵循的所有教程似乎都不起作用。

以下是用于我的结果页面的代码:

<?php
            $button = $_GET ['submit'];
            $search = $_GET ['search']; 
            if(!$button)
            echo "<p>Sorry but we can't find any results if you do not      submit a keyword</p>";
            else
            {
            if(strlen($search)<=1)
            echo "<p>Sorry but the search term you provided is too short for     us to find any items related.</p> ";
            else{
            echo "<p>You searched for <b>$search</b> <hr size='1'></br></p><p>If your site hasn't shown up just visit the Members area and submit it!</p>";
            mysql_connect("localhost","username","password");
            mysql_select_db("database");
            $search_exploded = explode (" ", $search);
            foreach($search_exploded as $search_each)
            {
            $x++;
            if($x==1)
            $construct .="keywords LIKE '%$search_each%'";
            else
            $construct .="AND keywords LIKE '%$search_each%'";
            }
            $construct ="SELECT * FROM searchengine WHERE $construct";
            $run = mysql_query($construct);
            $foundnum = mysql_num_rows($run);
            if ($foundnum==0)
            echo "<p>Sorry, there are no matching results for     <b>$search</b>.</br></br>1. 
            Try more general words. for example: If you want to search 'how     to create a website'
            then use general keyword like 'create' 'website'</br>2. Try different words with similar
             meaning</br>3. Please check your spelling.</br>4. If you have any ideas on sites you want to show up submit it to our database.</p>";
            else
            {
            echo "<p>We found $foundnum results!</p>";
            while($runrows = mysql_fetch_assoc($run))
            {
            $title = $runrows ['title'];
            $desc = $runrows ['description'];
            $url = $runrows ['url'];
            echo "
            <p><a href='$url'><b>$title</b></a><br>
            $desc<br>
            <a href='$url'>$url</a></p>
            ";
            }
            }
            }
            }
            ?>

如果有人有任何可能对我有帮助的想法,那就太棒了!

谢谢

构建分页的最基本方法是使用 LIMIT 和 OFFSET。

SELECT * FROM table LIMIT 10 OFFSET 0 // Fetch 10 rows from table starting from row 0
SELECT * FROM table LIMIT 10 OFFSET 10 // Fetch the next 10 rows from the table. starting from row 20

让我们尝试以下操作:

$limit = 10;
$pageNum = ( isset($_GET['page']) && $_GET['page'] > 0 ? $_GET['page'] : 0 );
$offset = ($pageNum * $limit);

$construct ="SELECT * FROM searchengine WHERE $construct ORDER BY id DESC LIMIT " . $limit . " OFFSET " . $offset;

print '<a href="/search.php?search=' . $search . '&page=' . $pageNum+1 . '">Next page</a>

通常,我想警告您不要使用旧的 php mySql 驱动程序,并直接从客户端将未经净化的数据插入查询中。但这是基础知识,写入您自己的代码样式。

我建议您查看PDO或MySqli,它们都支持准备的(kindof)语句,以便更安全地生成查询。

有好的一天。

最新更新