I've got a script that dynamically calls and displays images from a directory, what would be the best way to paginate this? I'd like to be able to control the number of images that are displayed per page through a variable within the script. I'm thinking of using URL varriables (ie - http://domain.com/page.php?page=1) but am unsure how to go about this.
Thanks for the help.
pagination is the same concept with or without sql. you just need your basic variables, then you can create the content you want. here's some quasi-code:
$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
}
hope that helps you get started!
This is a function I often use to do pagination. Hope it helps.
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));
This will return:
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
)
With all that data you are then pretty well armed to make the pagination links.
If you name your images 01.jpg, 02.jpg it makes it easier to paginate. Then use glob to get all the images into an array and sort it.
When in doubt use javascript! This might help too: http://www.webplicity.net/flexigrid/
Might be good for galery-like apps, though I've never tried it :)