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.
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.
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!
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 :)
Related
I'm making a new thread on this, as I'm actually somewhere now.
I've got a paging system, but there's a problem.
I work with DAO's and controllers.
Thing is, my second page (of my paging system) goes to index.php?page=2. The major problem here is that whenever you go to a page that doesn't exist in the index.php it redirects automatically to index.php. Page 2 isn't mentioned there as I can't mention every single page there as the pages will increase the more items there will be inserted.
Here's the entire code I'm using for the paging: (edited)
<?php
$mysqli = new mysqli("localhost", "wanthave", "wanthavepass", "wanthave");
$count_mem = $mysqli->query("SELECT `id` FROM `wanthave_items`");
$rows = $count_mem->num_rows;
$perPage = 5; // items to be shown per page
$num_pages = ceil($rows / $perPage);
$visiblePages = 5; // if current page is 7 show: 5,6,7,8,9,...
$visibleOffset = ceil($visiblePages / 2) - 1; // number of pages to show on the left and on the right of the current page
// Where do you use this ???
// $start = $page == 1 ? 0 : (($page - 1) * $perPage);
if ($num_pages > 1) {
$first = $last = $pagesStr = '';
echo $first . $pageStr . $last;
}
foreach($items as $item) {
echo "<li>
{$item['name']}
</li>";
}
for ($n = 1; $n < ($num_pages + 1); $n++) {
echo "<a href='index.php?page=$n'>$n</a>";
if ($n < $num_pages) echo ", ";
}
?>
my index.php
<?php
session_start();
define('DS', DIRECTORY_SEPARATOR);
define('WWW_ROOT', __DIR__ . DS);
$routes = array(
'home' => array(
'controller' => 'Item',
'action' => 'index'
),
'register' => array(
'controller' => 'Users',
'action' => 'register'
),
'login' => array(
'controller' => 'Users',
'action' => 'login'
),
'logout' => array(
'controller' => 'Users',
'action' => 'logout'
),
'item-detail' => array(
'controller' => 'Item',
'action' => 'detail'
),
);
if(empty($_GET['page'])) {
$_GET['page'] = 'home';
}
if(empty($routes[$_GET['page']])) {
header('Location: index.php');
exit();
}
$route = $routes[$_GET['page']];
$controllerName = $route['controller'] . 'Controller';
require_once WWW_ROOT . 'controller' . DS . $controllerName . ".php";
$controllerObj = new $controllerName();
$controllerObj->route = $route;
$controllerObj->filter();
$controllerObj->render();
This is quite a good post on simple pagination with PHP Limit pagination page number
With your example, for starter you should also validate that the page parameter is an integer and you can get partially rid of the very last if-else statement. So let's try optimizing the code a bit:
<?php
$mysqli = new mysqli("localhost", "wanthave", "wanthavepass", "wanthave");
$count_mem = $mysqli->query("SELECT `id` FROM `wanthave_items`");
$rows = $count_mem->num_rows;
$perPage = 5; // items to be shown per page
$num_pages = ceil($rows / $perPage);
$visiblePages = 5; // if current page is 7 show: 5,6,7,8,9,...
$visibleOffset = ceil($visiblePages / 2) - 1; // number of pages to show on the left and on the right of the current page
$page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;
// Where do you use this ???
// $start = $page == 1 ? 0 : (($page - 1) * $perPage);
if ($num_pages > 1) {
$first = $last = $pagesStr = '';
if($num_pages > $visiblePages){
// no need to show First page if already on it
if($page != 1){
$first = "<a href='index.php?page=1'>First</a>";
}
// no need to show Last page if already on it
if($page < $numPages){
$last = "<a href='index.php?page=$numPages'>Last</a>";
}
// the offset cannot be smaller or bigger than the min & max page number
$fromPage = ($page - $visibleOffset) < 1 ? 1 : ($page - $visibleOffset);
$toPage = ($page + $visibleOffset) > $numPage ? $numPage : ($page + $visibleOffset);
for($i=$fromPage; $i<=$toPage; $i++){
$pagesStr .= "<a href='index.php?page=$i'>$i</a>";
}
echo $first . $pageStr . $last;
} else {
// NOTE: You don't really need this ELSE section at all
// Where is $items defined ???
foreach($items as $item) {
echo "<li>
{$item['name']}
</li>";
}
for ($n = 1; $n < ($num_pages + 1); $n++) {
echo "<a href='index.php?page=$n'>$n</a>";
if ($n < $num_pages) echo ", ";
}
}
}
?>
NOTE:
If you choose to remove the ELSE seciton, make sure to remove the
if($num_pages > $visiblePages){
...
}
part as well. It's one unnecessary check less since you can simply use the $fromPage and $toPage to cycle all available pages.
I haven't tried this code so there might be bugs in it, but the important thing is to not use hardcoded values anywhere in your code and to try and optimize the pagination process as much as possible (and there are few things that could be modified here).
I have developed a Prestashop online store with a custom template.
Now, everything is OK, but the category product listing. I'm showing rows of three products, so, when showing the default pagination of 10 products per page, last row has only 1 product.
I cannot find how to change the pagination options so the user cannot choose the default values of 10,20 and 30 products per page and change them for 12,24,36
Thankyou in advance-
I found the solution (Prestashop 1.5.3.1).
Simply needed to edit FrontController.php. But, to make it cleaner I copied the pagination method to my overrided FrontController and changed only the line starting by $nArray = (int) Configuration::get('PS_PRODUCTS_PER_PAGE'):
<?php
class FrontController extends FrontControllerCore
{
public function pagination($nbProducts = 13)
{
if (!self::$initialized)
$this->init();
elseif (!$this->context)
$this->context = Context::getContext();
$nArray = (int) Configuration::get('PS_PRODUCTS_PER_PAGE') != 12 ?
array((int) Configuration::get('PS_PRODUCTS_PER_PAGE'), 12, 24, 50) :
array(12, 24, 50);
// Clean duplicate values
$nArray = array_unique($nArray);
asort($nArray);
$this->n = abs((int) (Tools::getValue('n', ((isset($this->context->cookie->nb_item_per_page) && $this->context->cookie->nb_item_per_page >= 10) ? $this->context->cookie->nb_item_per_page : (int) Configuration::get('PS_PRODUCTS_PER_PAGE')))));
$this->p = abs((int) Tools::getValue('p', 1));
if (!is_numeric(Tools::getValue('p', 1)) || Tools::getValue('p', 1) < 0)
Tools::redirect(self::$link->getPaginationLink(false, false, $this->n, false, 1, false));
$current_url = tools::htmlentitiesUTF8($_SERVER['REQUEST_URI']);
//delete parameter page
$current_url = preg_replace('/(\?)?(&)?p=\d+/', '$1', $current_url);
$range = 2; /* how many pages around page selected */
if ($this->p < 0)
$this->p = 0;
if (isset($this->context->cookie->nb_item_per_page) && $this->n != $this->context->cookie->nb_item_per_page && in_array($this->n, $nArray))
$this->context->cookie->nb_item_per_page = $this->n;
$pages_nb = ceil($nbProducts / (int) $this->n);
if ($this->p > $pages_nb && $nbProducts <> 0)
Tools::redirect(self::$link->getPaginationLink(false, false, $this->n, false, $pages_nb, false));
$start = (int) ($this->p - $range);
if ($start < 1)
$start = 1;
$stop = (int) ($this->p + $range);
if ($stop > $pages_nb)
$stop = (int) $pages_nb;
$this->context->smarty->assign('nb_products', $nbProducts);
$pagination_infos = array(
'products_per_page' => (int) Configuration::get('PS_PRODUCTS_PER_PAGE'),
'pages_nb' => $pages_nb,
'p' => $this->p,
'n' => $this->n,
'nArray' => $nArray,
'range' => $range,
'start' => $start,
'stop' => $stop,
'current_url' => $current_url
);
$this->context->smarty->assign($pagination_infos);
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I'm looking for an example algorithm of smart pagination. By smart, what I mean is that I only want to show, for example, 2 adjacent pages to the current page, so instead of ending up with a ridiculously long page list, I truncate it.
Here's a quick example to make it clearer... this is what I have now:
Pages: 1 2 3 4 [5] 6 7 8 9 10 11
This is what I want to end up with:
Pages: ... 3 4 [5] 6 7 ...
(In this example, I'm only showing 2 adjacent pages to the current page)
I'm implementing it in PHP/Mysql, and the "basic" pagination (no trucating) is already coded, I'm just looking for an example to optimize it... It can be an example in any language, as long as it gives me an idea as to how to implement it...
Here is some code based on original code from this very old link. It uses markup compatible with Bootstrap's pagination component, and outputs page links like this:
[1] 2 3 4 5 6 ... 100
1 [2] 3 4 5 6 ... 100
...
1 2 ... 14 15 [16] 17 18 ... 100
...
1 2 ... 97 [98] 99 100
<?php
// How many adjacent pages should be shown on each side?
$adjacents = 3;
//how many items to show per page
$limit = 5;
// if no page var is given, default to 1.
$page = (int)$_GET["page"] ?? 1;
//first item to display on this page
$start = ($page - 1) * $limit;
/* Get data. */
$data = $db
->query("SELECT * FROM mytable LIMIT $start, $limit")
->fetchAll();
$total_pages = count($data);
/* Setup page vars for display. */
$prev = $page - 1;
$next = $page + 1;
$lastpage = ceil($total_pages / $limit);
//last page minus 1
$lpm1 = $lastpage - 1;
$first_pages = "<li class='page-item'><a class='page-link' href='?page=1'>1</a></li>" .
"<li class='page-item'><a class='page-link' href='?page=2'>2</a>";
$ellipsis = "<li class='page-item disabled'><span class='page-link'>...</span></li>";
$last_pages = "<li class='page-item'><a class='page-link' href='?page=$lpm1'>$lpm1</a></li>" .
"<li class='page-item'><a class='page-link' href='?page=$lastpage'>$lastpage</a>";
$pagination = "<nav aria-label='page navigation'>";
$pagincation .= "<ul class='pagination'>";
//previous button
$disabled = ($page === 1) ? "disabled" : "";
$pagination.= "<li class='page-item $disabled'><a class='page-link' href='?page=$prev'>« previous</a></li>";
//pages
//not enough pages to bother breaking it up
if ($lastpage < 7 + ($adjacents * 2)) {
for ($i = 1; $i <= $lastpage; $i++) {
$active = $i === $page ? "active" : "";
$pagination .= "<li class='page-item $active'><a class='page-link' href='?page=$i'>$i</a></li>";
}
} elseif($lastpage > 5 + ($adjacents * 2)) {
//enough pages to hide some
//close to beginning; only hide later pages
if($page < 1 + ($adjacents * 2)) {
for ($i = 1; $i < 4 + ($adjacents * 2); $i++) {
$active = $i === $page ? "active" : "";
$pagination .= "<li class='page-item $active'><a class='page-link' href='?page=$i'>$i</a></li>";
}
$pagination .= $ellipsis;
$pagination .= $last_pages;
} elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2)) {
//in middle; hide some front and some back
$pagination .= $first_pages;
$pagination .= $ellipsis
for ($i = $page - $adjacents; $i <= $page + $adjacents; $i++) {
$active = $i === $page ? "active" : "";
$pagination .= "<li class='page-item $active'><a class='page-link' href='?page=$i'>$i</a></li>";
}
$pagination .= $ellipsis;
$pagination .= $last_pages;
} else {
//close to end; only hide early pages
$pagination .= $first_pages;
$pagination .= $ellipsis;
$pagination .= "<li class='page-item disabled'><span class='page-link'>...</span></li>";
for ($i = $lastpage - (2 + ($adjacents * 2)); $i <= $lastpage; $i++) {
$active = $i === $page ? "active" : "";
$pagination .= "<li class='page-item $active'><a class='page-link' href='?page=$i'>$i</a></li>";
}
}
}
//next button
$disabled = ($page === $last) ? "disabled" : "";
$pagination.= "<li class='page-item $disabled'><a class='page-link' href='?page=$next'>next »</a></li>";
$pagination .= "</ul></nav>";
if($lastpage <= 1) {
$pagination = "";
}
echo $pagination;
foreach ($data as $row) {
// display your data
}
echo $pagination;
Kinda late =), but here is my go at it:
function Pagination($data, $limit = null, $current = null, $adjacents = null)
{
$result = array();
if (isset($data, $limit) === true)
{
$result = range(1, ceil($data / $limit));
if (isset($current, $adjacents) === true)
{
if (($adjacents = floor($adjacents / 2) * 2 + 1) >= 1)
{
$result = array_slice($result, max(0, min(count($result) - $adjacents, intval($current) - ceil($adjacents / 2))), $adjacents);
}
}
}
return $result;
}
Example:
$total = 1024;
$per_page = 10;
$current_page = 2;
$adjacent_links = 4;
print_r(Pagination($total, $per_page, $current_page, $adjacent_links));
Output (# Codepad):
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Another example:
$total = 1024;
$per_page = 10;
$current_page = 42;
$adjacent_links = 4;
print_r(Pagination($total, $per_page, $current_page, $adjacent_links));
Output (# Codepad):
Array
(
[0] => 40
[1] => 41
[2] => 42
[3] => 43
[4] => 44
)
I started from the lazaro's post and tried to make a robust and light algorithm with javascript/jquery...
No additional and/or bulky pagination libraries needed...
Look on fiddle for an live example: http://jsfiddle.net/97JtZ/1/
var totalPages = 50, buttons = 5;
var currentPage = lowerLimit = upperLimit = Math.min(9, totalPages);
//Search boundaries
for (var b = 1; b < buttons && b < totalPages;) {
if (lowerLimit > 1 ) { lowerLimit--; b++; }
if (b < buttons && upperLimit < totalPages) { upperLimit++; b++; }
}
//Do output to a html element
for (var i = lowerLimit; i <= upperLimit; i++) {
if (i == currentPage) $('#pager').append('<li>' + i + '</li> ');
else $('#pager').append('<li><em>' + i + '</em></li> ');
}
List<int> pages = new List<int>();
int pn = 2; //example of actual pagenumber
int total = 8;
for(int i = pn - 9; i <= pn + 9; i++)
{
if(i < 1) continue;
if(i > total) break;
pages.Add(i);
}
return pages;
I made a pagination class and put in on Google Code a while ago. Check it out its pretty simple
http://code.google.com/p/spaceshipcollaborative/wiki/PHPagination
$paging = new Pagination();
$paging->set('urlscheme','class.pagination.php?page=%page%');
$paging->set('perpage',10);
$paging->set('page',15);
$paging->set('total',3000);
$paging->set('nexttext','Next Page');
$paging->set('prevtext','Previous Page');
$paging->set('focusedclass','selected');
$paging->set('delimiter','');
$paging->set('numlinks',9);
$paging->display();
I would use something simple on the page you are showing the paginator, like:
if (
$page_number == 1 || $page_number == $last_page ||
$page_number == $actual_page ||
$page_number == $actual_page+1 || $page_number == $actual_page+2 ||
$page_number == $actual_page-1 || $page_number == $actual_page-2
) echo $page_number;
You can adapt it to show each 10 or so pages with % operator ...
I think using switch() case would be better in this case, I just don't remember the syntax now
Keep it Simple :)
If it's possible to generate the pagination on the client, I would suggest my new Pagination plugin: http://www.xarg.org/2011/09/jquery-pagination-revised/
The solution to your question would be:
$("#pagination").paging(1000, { // Your number of elements
format: '. - nncnn - ', // Format to get Pages: ... 3 4 [5] 6 7 ...
onSelect: function (page) {
// add code which gets executed when user selects a page
},
onFormat: function (type) {
switch (type) {
case 'block': // n and c
return '<a>' + this.value + '</a>';
case 'fill': // -
return '...';
case 'leap': // .
return 'Pages:';
}
}
});
The code of the CodeIgniter pagination-class can be found on GitHub
(what you call) Smart pagination can be achieved by configuration.
$config['num_links'] = 2;
The number of "digit" links you would like before and after the
selected page number. For example, the number 2 will place two digits
on either side, as in the example links at the very top of this page.
So I'm doing this in PHP but it is a logic issue so I'll try to write it as generically as possible.
To start here's how this pagination script works:
for (draw first three pages links)
if (draw ellipsis (...) if there are pages between #1's pages and #3's pages)
for (draw current page and two pages on each side of it links)
if (draw elipsis (...) if there are pages between #3's pages and #5's pages)
for (draw final three pages links)
The problem is that when there are low amounts of pages (I noticed this when the page count was at 10) there should be an ellipsis but none is drawn.
Onto the code:
$page_count = 10; //in actual code this is set properly
$current_page = 1; //in actual code this is set properly
for ($i = 1;$i <= 3;$i++)
{
if ($page_count >= $i)
echo $i;
}
if ($page_count > 3 && $current_page >= 7)
echo "...";
for ($i = $current_page - 2;$i <= current_page + 2;$i++)
{
if ($i > 3 && $i < $page_count - 2)
echo $i;
}
if ($page_count > 13 && $current_page < $page_count - 5)
echo "...";
for ($i = $page_count - 2;$i <= $page_count;$i++)
{
if ($page_count > 3)
echo $i;
}
So I figure the best idea would to be to modify one of the two ellipsis if statements to include a case like this, however I've tried and am stumped.
Also please note that I condensed this code for readability sake so please don't give tips like "those for loops are ineffective because they will recalculate current_page - 2 for each iteration" because I know :)
For those whom want to see a breakdown of how this logic currently works, here is example output ( modified ) with iterating $page_count and $current_page.
http://rafb.net/p/TNa56h71.html
<?php
/**
* windowsize must be odd
*
* #param int $totalItems
* #param int $currentPage
* #param int $windowSize
* #param int $anchorSize
* #param int $itemsPerPage
* #return void
*/
function paginate($totalItems, $currentPage=1, $windowSize=3, $anchorSize=3, $itemsPerPage=10) {
$halfWindowSize = ($windowSize-1)/2;
$totalPages = ceil($totalItems / $itemsPerPage);
$elipsesCount = 0;
for ($page = 1; $page <= $totalPages; $page++) {
// do we display a link for this page or not?
if ( $page <= $anchorSize ||
$page > $totalPages - $anchorSize ||
($page >= $currentPage - $halfWindowSize &&
$page <= $currentPage + $halfWindowSize) ||
($page == $anchorSize + 1 &&
$page == $currentPage - $halfWindowSize - 1) ||
($page == $totalPages - $anchorSize &&
$page == $currentPage + $halfWindowSize + 1 ))
{
$elipsesCount = 0;
if ($page == $currentPage)
echo ">$page< ";
else
echo "[$page] ";
// if not, have we already shown the elipses?
} elseif ($elipsesCount == 0) {
echo "... ";
$elipsesCount+=1; // make sure we only show it once
}
}
echo "\n";
}
//
// Examples and output
//
paginate(1000, 1, 3, 3);
// >1< [2] [3] ... [98] [99] [100]
paginate(1000, 7, 3, 3);
// [1] [2] [3] ... [6] >7< [8] ... [98] [99] [100]
paginate(1000, 4, 3, 3);
// [1] [2] [3] >4< [5] ... [98] [99] [100]
paginate(1000, 32, 3, 3);
// [1] [2] [3] ... [31] >32< [33] ... [98] [99] [100]
paginate(1000, 42, 7, 2);
// [1] [2] ... [39] [40] [41] >42< [43] [44] [45] ... [99] [100]
This is probably an overcomplicated solution, but it works.
I've used an array here instead of just printing, which lets me "do-over" the logic.
Part of the problem occurs when "left and right of page" happens to coincide with left-and-right shoulders.
function cdotinator ( $current_page, $page_count )
{
$stepsize = 3;
$elipse = '...';
# Simple Case.
if ( $page_count <= 2 * $stepsize )
{
$out = range( 1, $page_count );
$out[$current_page - 1 ] = '*' . $current_page . '*';
return $out;
}
#Complex Case
# 1) Create All Pages
$out = range( 1, $page_count );
# 2 ) Replace "middle" pages with "." placeholder elements
for( $i = $stepsize+1 ; $i <= ( $page_count - $stepsize ) ; $i ++ )
{
$out[ $i - 1 ] = '.' ;
}
# 3.1 ) Insert the pages around the current page
for( $i = max(1,( $current_page - floor($stepsize / 2) )) ;
$i <= min( $page_count,( $current_page + floor( $stepsize/2)));
$i ++ )
{
$out[ $i - 1] = $i;
}
# 3.2 Bold Current Item
$out[ $current_page - 1 ] = '*' . $current_page . '*' ;
# 4 ) Grep out repeated '.' sequences and replace them with elipses
$out2 = array();
foreach( $out as $i => $v )
{
# end, current == peek()
end($out2);
if( current($out2) == $elipse and $v == '.' )
{
continue;
}
if( $v == '.' )
{
$out2[] = $elipse;
continue;
}
$out2[]= $v;
}
return $out2;
}
Output can be seen here: http://dpaste.com/92648/
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.
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.
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!
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 :)