需要一个Pagination PHP代码来集成我的SEARCH php脚本

时间:2012-10-17 16:49:28

标签: php search pagination integrate

已经过了一个月,我真的搞砸了尝试将php分页代码集成到我的搜索脚本中。提到谷歌的大部分教程,但徒劳无功。任何帮助将非常感激。我走了......

<?php
 ob_start();
 session_start();
 $_GET['term'] = trim($_GET['term']);
 $output = preg_replace('!\s+!', ' ', $_GET['term']);
 if(empty($_GET['term'])|| preg_match("/^[@!#\$\^%&*()+=\-\[\]\\\';,\.\/\{\}\|\":<>\?\ _ ]+$/i", $_GET['term']) || $output== ' ' || $_GET['term']== "%24_GET%5B%27term%27%5D")
 {
 echo "<BR>";
 echo "<BR>";
 echo("Please enter a Valid Search term");
 }
 else
 {
    mysql_connect("localhost", "root", "root");
    mysql_select_db("search");
    $_GET['term'] = explode(' ', $_GET['term']);
    foreach($_GET['term'] AS $_GET['term'])
     {
     $_GET['term'] = trim($_GET['term']);
 $sql = mysql_query("SELECT DISTINCT * FROM searchengine WHERE pagecontent LIKE '%" . str_replace(' ', "%' AND pagecontent LIKE '%", $_GET['term'])."%' LIMIT 0,10");
   while($ser = mysql_fetch_array($sql)) {
       echo "<BR>";
        echo "<b><u><a href='$ser[pageurl]'>$ser[title]</a></u></b>";
        echo "<BR>";
        echo("<span class='style_block'>{$ser['pagecontent']}</span>");
        echo "<BR>";
        echo ("<a href='$ser[pageurl]'>$ser[pageurl]</a>");
        echo "<BR>";
        echo "<BR>";
       } 
    }
$count=mysql_num_rows($sql);
if($count==0)
{
 echo "<BR>";
 echo "<BR>";
echo "Sorry, No News material was found... Please refine your search criteria and try again.";
}
    }
?>

1 个答案:

答案 0 :(得分:2)

除了Luc M在他的评论中提到的问题(你在向前推进之前肯定会解决),你几乎就在那里。

您需要考虑以下几点:每页显示多少条记录,以及您所在的页面。这些将指示您需要检索和显示的记录。那么,你怎么做呢?

通过在SQL查询中使用LIMIT子句,您的代码中已经涵盖了第一点。第二点是开始时稍微复杂一点。您需要一种识别您所在页面的方法。这可能最容易通过GET变量来识别,例如http://site.com/search.php?page=2。现在,为了实现这一点,你需要这些内容:

$recordsPerPage = 10; // although you may want to have this as a GET or POST variable as well, so the user can decide
if(isset($_GET['page']) // this ensures a default value
{
    $currentPage = $_GET['page'];
}
else
{
    $currentPage = 1;
}

然后,对于您的SQL查询,您希望构建如下内容:

$query = "SELECT * FROM table_name LIMIT " . $recordsPerPage . " OFFSET " . ($currentPage - 1)*$recordsPerpage . ";";

SQL的OFFSET子句和LIMIT基本上说“从结果编号x开始选择这么多记录”。您在$currentPage - 1上进行了偏移,因为第一页不需要偏移量,而第二页只需要偏移量,但是在第一页上显示了很多记录,依此类推。

要为分页数据创建导航,您需要了解结果集中有多少条记录,这可以通过PHP的count($array)函数完成。然后,要查找页数,只需使用以下内容:

$ numPages = ceil(count($ array)/ $ recordsPerPage);

其中$array是来自SQL查询的数据集。 ceil()函数将结果舍入到下一个整数。

获得此结果后,您只需输出指向每个页面的链接,只需使用for循环即可:

for($i = 0; i < $numPages; i++)
{
    echo '<a href="/search.php?page="' . $i+1 . '>' . $i+1 . '</a>';
}

要创建第一页,上一页,下一页和最后一页链接,您需要执行以下操作:

$firstPage = 1;
$previousPage = $currentPage - 1; // you may want to check here or elsewhere to make sure you have no page zero
$nextPage = $currentPage + 1; // may also want to make sure you don't go past the last page
$lastPage = $numPages;

然后可以将这些值放入生成的链接中。

同样,我将向您推荐Luc M的评论......这些需要修复,请查看mysqli函数,而不是您当前使用的现已弃用的mysql_*()函数,确保在使用前清理任何用户输入的数据,并考虑查看MVC设计模式。

希望这会帮助你。