在PHP中不使用数据库进行分页


Pagination without using database in PHP

我正在尝试创建一个网页,每次显示存储在一个目录中的10个文件。不过我不想使用数据库。这就是我到目前为止所拥有的。

<?php 
$exclude = array("index.php");
$cssfiles = array_diff(glob("*.php"), $exclude); 
foreach ($cssfiles as $cssfile) {
$filename = "http://example.com/lessons/css/".$cssfile;
outputtags($filename,true,true); 
}
?>

这会打印出所有的结果,我不知道如何在不使用数据库的情况下只显示前十个结果,然后当用户点击下十个结果时。我认为仅仅为了这个目的使用数据库是没有意义的。

EDIT我之所以要这样做,是因为我遇到了max_user_connection错误。

您可以通过将文件存储到数组中并根据自己的意愿进行排序来实现这一点,如下所示:

    $exclude = array("index.php");
    $cssfiles = array_diff(glob("*.php"), $exclude); 
    $files = array();
    foreach ($cssfiles as $cssfile) {
    $filename = "http://example.com/lessons/css/".$cssfile;
       $files[] = $filename;
    }
    asort($files);
    // Pagination start from here
    $page = 1; // You will get this parameter from the url using $_GET['page'] for instance
    $limit  = 10; // Number of files to display.
    $offset = (($page-1) * $limit);
    $max = ($page * $limit);
    $max = $max > count($files)  ? count($files) : $max;
    for ($i=$offset; $i<$max; $i++) {
        echo $files[$i] . PHP_EOL;
    }
    echo 'Total Pages : ', count($files). PHP_EOL;
    echo 'Page number : ' , $page;

也许您可以使用ajax并提取分页页面,以避免每次获取所有文件。

这取决于您希望如何选择这十个页面。可以使用将文件0-9列为并且可以从10-19计数的CCD_,。。。,在用户请求的页面范围上展开。

但是,当添加一个文件时,系统会出现故障。在这种情况下,将一些排序信息加载/保存到会话/cookie可以解决问题。

编辑:然而,使用数据库是此类任务的标准。即使您不喜欢它们,您也很可能需要它们来执行更复杂的任务,这些任务需要排序、搜索或连接多个数据集,而文件系统功能无法实现这些任务。