没有SQL的PHP​​动态分页

时间:2008-10-16 02:24:12

标签: php pagination

我有一个动态调用并显示目录中图像的脚本,这是分页的最佳方法吗?我希望能够通过脚本中的变量控制每页显示的图像数量。我正在考虑使用URL varriables(即 - http://domain.com/page.php?page=1),但我不确定如何解决这个问题。

感谢您的帮助。

4 个答案:

答案 0 :(得分:10)

这是我经常用来做分页的功能。希望它有所帮助。

function paginate($page, $total, $per_page) {
    if(!is_numeric($page)) { $page = 1; }
    if(!is_numeric($per_page)) { $per_page = 10; }
    if($page > ceil($total / $per_page)) $page = 1;
    if($page == "" || $page == 0) { 
        $page = 1;
        $start = 0;
        $end = $per_page;
    } else {
        $start = ($page * $per_page) - ($per_page);
        $end = $per_page;
    }

    $prev_page = "";
    $next_page = "";
    $all_pages = array();
    $selected = "";
    $enabled = false;

    if($total > $per_page) {
        $enabled = true;
        $prev = $page - 1;
        $prev_page = ($prev == 0) ? 0 : $prev;

        $next = $page + 1;
        $total_pages = ceil($total/$per_page);

        $next_page = ($next <= $total_pages) ? $next : 0;

        for($x=1;$x<=$total_pages;$x++) {
            $all_pages[] = $x;
            $selected = ($x == $page) ? $x : $selected; 
        }
    }

    return array(
        "per_page" => $per_page,
        "page" => $page,
        "prev_page" => $prev_page,
        "all_pages" => $all_pages,
        "next_page" => $next_page,
        "selected" => $selected,
        "start" => $start,
        "end" => $end,
        "enabled" => $enabled
    );
}

// ex: we are in page 2, we have 50 items, and we're showing 10 per page
print_r(paginate(2, 50, 10));

这将返回:

Array
(
    [per_page] => 10
    [page] => 2
    [prev_page] => 1
    [all_pages] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
            [4] => 5
        )
    [next_page] => 3
    [selected] => 2
    [start] => 10
    [end] => 10
    [enabled] => 1
)

有了所有这些数据,你就可以很好地制作分页链接了。

答案 1 :(得分:9)

分页是与sql相同还是没有sql的概念。你只需要你的基本变量,然后就可以创建你想要的内容了。这是一些准代码:

$itemsPerPage = 5;

$currentPage = isset($_GET['page']) ? $_GET['page'] : 1;
$totalItems = getTotalItems();
$totalPages = ceil($totalItems / $itemsPerPage);

function getTotalItems() {
// since they're images, perhaps we'll scan a directory of images to determine
// how many images we have in total
}

function getItemsFromPage($page, $itemsPerPage) {
// function to grab $itemsPerPage based on which $page we're on
}

function getPager($totalPages, $currentPage) {
// build your pager
}

希望能帮助您入门!

答案 2 :(得分:0)

如果您将图像命名为01.jpg,02.jpg,则可以更轻松地进行分页。然后使用glob将所有图像放入一个数组中并对其进行排序。

答案 3 :(得分:0)

如有疑问,请使用javascript!这也可能有所帮助:http://www.webplicity.net/flexigrid/

可能对类似galery的应用程序有好处,但我从未尝试过它。)