使用 PHP 的上一页/下一页链接

问题描述 投票:0回答:3

我有 80 个 PHP 页面 - 我想在每个页面上都有下一页/后退按钮,自动链接到上一页/下一页。页面按顺序编号(page1.php、page2.php、page3 等)。

我想要一种更简单的方法,而不是必须手动链接每个学生个人资料页面上的每个按钮才能转到下一个/上一个学生页面。

有人知道如何做到这一点吗?

php navigation
3个回答
3
投票

这是一个相对稳健的解决方案(考虑到需求):

$pinfo = pathinfo($_SERVER["SCRIPT_FILENAME"]);
$reqpath = dirname($_SERVER["REQUEST_URI"]);

if(preg_match("/(.*?)(\d+)\.php/",  $pinfo["basename"], $matches)) {
    $fnbase = $matches[1];
    $fndir = $pinfo["dirname"];
    $current = intval($matches[2]);
    $next = $current + 1;
    $prior = $current - 1;
    $next_file = $fndir . DIRECTORY_SEPARATOR . $fnbase . $next . ".php";
    $prior_file = $fndir . DIRECTORY_SEPARATOR . $fnbase . $prior . ".php";

    if(!file_exists($next_file)) $next_file = false;
    if(!file_exists($prior_file)) $prior_file = false;


    if($prior_file) {
        $link = "$reqpath/" . basename($prior_file);

        echo "<a href=\"$link\">Prior</a>";
    }

    if($prior_file && $next_file) {
        echo " / ";
    }

    if($next_file) {
        $link = "$reqpath/" . basename($next_file);

        echo "<a href=\"$link\">Next</a>";
    }
}
  • 它检查下一个/前一个文件是否确实存在
  • 它支持多种枚举,例如
    {bla1, bla2, bla3}
    {foo1, foo2, foo3}

2
投票

你可以做这样可怕的事情:

// Get the current file name
$currentFile = $_SERVER["SCRIPT_NAME"];
$currentNumber = preg_replace('/\D/', '', $currentFile);
$next = $currentNumber + 1;
echo "<a href='page$next.php'>next page</a>";

类似的东西可以用来查找上一页。

这可能不是一个好主意,原因如下:

  • 页面名称仍然硬编码为
    page$next.php
  • 如果页面 ID 有任何间隙,您将引导用户访问 404
  • 如果页面被重命名,这将会非常糟糕

0
投票

我想你可以检查下面的代码。很简单。

<div>
<?php
$maxpage = 80;
if(!isset($_SESSION["currentPage"]))
    $_SESSION["currentPage"] = 0;

if($_SESSION["currentPage"] > 1)
{
?>
<a href="page<?php echo ($_SESSION["currentPage"] -1); ?>.php">Previous </a>
<?php
}
if ($_SESSION["currentPage"] < $maxpage )
{
?>
<a href="page<?php echo ($_SESSION["currentPage"] +1); ?>.php">Next </a>
<?php
}
?>
</div>

希望这对您有帮助。

普拉萨德。

© www.soinside.com 2019 - 2024. All rights reserved.