I have a table loaded via AJAX and along with the table the pagination is also loaded through AJAX. The table contains a list of all users on my site limited to 30 at a time.
This is how I'm returning the response to the JavaScript from the controller:
$users = $this->users_m->get_users($type, $offset);
$num_rows = $this->users_m->user_stats($type);
$config['per_page'] = 30;
$config['num_links'] = 5;
$config['total_rows'] = $num_rows[0];
$this->pagination->initialize($config);
echo json_encode(array(
'users' => $users,
'pagination' => $this->pagination->create_links()
));
All is well except the pagination is never correct. The first time it is but on subsequent requests it is not.
When using the pagination class in a non AJAX page, the page number I click becomes the active one. Here page 1 is always active (surrounded by <strong> tags as opposed to being a link). Secondly the numbers never change. I get:
[1] [2] [3] [4] [5] [6] [>] [Last >]
every time. Even if I click last I get the same numbers back, it doesn't change.
How to get the pagination class to work with AJAX?
Ok I came up with a working solution that I will post here in case anyone else has the same issue.
I used the pagination class found here:
http://www.catchmyfame.com/2007/07/28/finally-the-simple-pagination-class/
https://github.com/catchmyfame/PHP-Pagination-Class/blob/master/paginator.class.php
but modified it to work both as a CI library and also with my particular javascript. Create a new file called
Pagination_ajax.php
and put it in the same location as the default pagination class in
/system/libraries.
This is the modified class:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
* PHP Pagination Class
* #author admin#catchmyfame.com - http://www.catchmyfame.com
* #version 2.0.0
* #date October 18, 2011
* #copyright (c) admin#catchmyfame.com (www.catchmyfame.com)
* #license CC Attribution-ShareAlike 3.0 Unported (CC BY-SA 3.0) - http://creativecommons.org/licenses/by-sa/3.0/
*/
class Pagination_ajax {
var $items_per_page;
var $items_total;
var $current_page;
var $num_pages;
var $mid_range;
var $low;
var $limit;
var $return;
var $default_ipp;
var $querystring;
var $ipp_array;
function Paginator()
{
$this->current_page = 1;
$this->mid_range = 7;
$this->ipp_array = array(10,25,50,100,'All');
$this->items_per_page = (!empty($_GET['ipp'])) ? $_GET['ipp']:$this->default_ipp;
}
function paginate()
{
if(!isset($this->default_ipp)) $this->default_ipp=25;
if($_GET['ipp'] == 'All')
{
$this->num_pages = 1;
// $this->items_per_page = $this->default_ipp;
}
else
{
if(!is_numeric($this->items_per_page) OR $this->items_per_page <= 0) $this->items_per_page = $this->default_ipp;
$this->num_pages = ceil($this->items_total/$this->items_per_page);
}
$this->current_page = (isset($_GET['page'])) ? (int) $_GET['page'] : 1 ; // must be numeric > 0
$prev_page = $this->current_page-1;
$next_page = $this->current_page+1;
if($_GET)
{
$args = explode("&",$_SERVER['QUERY_STRING']);
foreach($args as $arg)
{
$keyval = explode("=",$arg);
if($keyval[0] != "page" And $keyval[0] != "ipp") $this->querystring .= "&" . $arg;
}
}
if($_POST)
{
foreach($_POST as $key=>$val)
{
if($key != "page" And $key != "ipp") $this->querystring .= "&$key=$val";
}
}
if($this->num_pages > 10)
{
$this->return = ($this->current_page > 1 And $this->items_total >= 10) ? "<a data-page=\"$prev_page\" class=\"paginate\" href=\"#\">« Previous</a> ":"<span class=\"inactive\" href=\"#\">« Previous</span> ";
$this->start_range = $this->current_page - floor($this->mid_range/2);
$this->end_range = $this->current_page + floor($this->mid_range/2);
if($this->start_range <= 0)
{
$this->end_range += abs($this->start_range)+1;
$this->start_range = 1;
}
if($this->end_range > $this->num_pages)
{
$this->start_range -= $this->end_range-$this->num_pages;
$this->end_range = $this->num_pages;
}
$this->range = range($this->start_range,$this->end_range);
for($i=1;$i<=$this->num_pages;$i++)
{
if($this->range[0] > 2 And $i == $this->range[0]) $this->return .= " ... ";
// loop through all pages. if first, last, or in range, display
if($i==1 Or $i==$this->num_pages Or in_array($i,$this->range))
{
$this->return .= ($i == $this->current_page And $_GET['page'] != 'All') ? "<a class=\"current\" href=\"#\">$i</a> ":"<a data-page=\"$i\" class=\"paginate\" href=\"#\">$i</a> ";
}
if($this->range[$this->mid_range-1] < $this->num_pages-1 And $i == $this->range[$this->mid_range-1]) $this->return .= " ... ";
}
$this->return .= (($this->current_page < $this->num_pages And $this->items_total >= 10) And ($_GET['page'] != 'All') And $this->current_page > 0) ? "<a data-page=\"$next_page\" class=\"paginate\" href=\"#\">Next »</a>\n":"<span class=\"inactive\" href=\"#\">» Next</span>\n";
$this->return .= ($_GET['page'] == 'All') ? "<a class=\"current\" style=\"margin-left:10px\" href=\"#\">All</a> \n":"<a data-page=\"1\" data-all=\"true\" class=\"paginate\" style=\"margin-left:10px\" href=\"#\">All</a> \n";
}
else
{
for($i=1;$i<=$this->num_pages;$i++)
{
$this->return .= ($i == $this->current_page) ? "<a class=\"current\" href=\"#\">$i</a> ":"<a data-page=\"$i\" class=\"paginate\" href=\"#\">$i</a> ";
}
$this->return .= "<a data-page=\"1\" data-all=\"true\" class=\"paginate\" href=\"#\">All</a> \n";
}
$this->low = ($this->current_page <= 0) ? 0:($this->current_page-1) * $this->items_per_page;
if($this->current_page <= 0) $this->items_per_page = 0;
$this->limit = ($_GET['ipp'] == 'All') ? "":" LIMIT $this->low,$this->items_per_page";
}
function display_items_per_page()
{
$items = '';
if(!isset($_GET[ipp])) $this->items_per_page = $this->default_ipp;
foreach($this->ipp_array as $ipp_opt) $items .= ($ipp_opt == $this->items_per_page) ? "<option selected value=\"$ipp_opt\">$ipp_opt</option>\n":"<option value=\"$ipp_opt\">$ipp_opt</option>\n";
return "<span class=\"paginate\">Items per page:</span><select class=\"paginate\" onchange=\"window.location='$_SERVER[PHP_SELF]?page=1&ipp='+this[this.selectedIndex].value+'$this->querystring';return false\">$items</select>\n";
}
function display_jump_menu()
{
for($i=1;$i<=$this->num_pages;$i++)
{
$option .= ($i==$this->current_page) ? "<option value=\"$i\" selected>$i</option>\n":"<option value=\"$i\">$i</option>\n";
}
return "<span class=\"paginate\">Page:</span><select class=\"paginate\" onchange=\"window.location='$_SERVER[PHP_SELF]?page='+this[this.selectedIndex].value+'&ipp=$this->items_per_page$this->querystring';return false\">$option</select>\n";
}
function display_pages()
{
return $this->return;
}
}
You can do a diff between this and the original download to see exactly what I changed.
Controller code:
public function get_users() {
// pagination
$this->load->library('pagination_ajax');
$pages = new Pagination_ajax;
$num_rows = $this->users_m->user_stats(); // this is the COUNT(*) query that gets the total record count from the table you are querying
$pages->items_total = $num_rows[0];
$pages->mid_range = 10; // number of links you want to show in the pagination before the "..."
$pages->paginate();
$users = $this->users_m->get_users($pages->limit); // your query
echo json_encode(array(
'users' => $users,
'pagination' => $pages->display_pages()
));
}
Model Code:
public function get_users($limit) {
$sql = "SELECT *
FROM `users`
$limit";
$query = $this->db->query($sql);
$users = array();
foreach ($query->result() as $row) {
$users[] = array(
'user_id' => $row->user_id,
'username' => $row->username,
'email' => $row->email
);
}
return $users;
}
JQuery:
// pagination
$('#pagination a').live('click', function() {
var $this = $(this);
var page = $this.data('page');
var ipp = ($this.data('all')) ? 'All' : 30; // I am returning 30 results per page, change to what you want
$.ajax({
url: '/admin/users/get_users?page=' + page + '&ipp=' + ipp,
dataType: 'json',
success: function(response) {
for(var i=0; i<response.users.length; i++) {
var user = response.users[i];
var tr = '<tr>' +
'<td>' + user.user_id + '</td>' +
'<td>' + user.username + '</td>' +
'<td>' + user.email + '</td>' +
'</tr>';
$('table tbody').append(tr);
}
// pagination
$('#pagination').html(response.pagination);
},
error: function() {
alert('An error occurred');
}
});
return false;
});
HTML
<h1>Users</h1>
<table>
<thead>
<th>ID</th>
<th>Username</th>
<th>Email</th>
</thead>
<tbody></tbody>
</table>
<div id="pagination"></div>
CSS
#pagination { overflow: hidden; margin-bottom: 10px; text-align: center; }
#pagination a { display: inline-block; padding: 3px 5px; font-size: 14px; color: #333; border-radius: 3px; text-shadow: 0 0 1px #fff; border: 1px solid #ccc;
background: #ffffff;
background: -moz-linear-gradient(top, #ffffff 0%, #f6f6f6 47%, #ededed 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffffff), color-stop(47%,#f6f6f6), color-stop(100%,#ededed));
background: -webkit-linear-gradient(top, #ffffff 0%,#f6f6f6 47%,#ededed 100%);
background: -o-linear-gradient(top, #ffffff 0%,#f6f6f6 47%,#ededed 100%);
background: -ms-linear-gradient(top, #ffffff 0%,#f6f6f6 47%,#ededed 100%);
background: linear-gradient(to bottom, #ffffff 0%,#f6f6f6 47%,#ededed 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#ededed',GradientType=0 );
}
#pagination a:hover { border: 1px solid #333; }
#pagination a.current { color: #f00; }
Hope someone finds this useful.
I did this in this way, add jquery library
pagination class:
$html = "<a style=\"cursor:pointer\" onclick=\"pagination('$url','$par','$div')\" >$text</a>";
else:
$html = "<a style=\"cursor:pointer\" onclick=\"pagination('$url','','$div')\" >$text</a>";
JS
var ServerCall = function(_url,_data,callback){
$('#Spinner').center().show();
_data = (_data == null)?'':_data;
$.ajax({
type: "POST",
url: _url,
data: 'ajax=1&'+_data,
dataType:'html',
success:
function(result) {
$('#Spinner').hide();
callback(result);
},
error: function (data, status, e){
$('#Spinner').hide();
}
});
};
var pagination = function (_url,_params,_div)
{
ServerCall(_url,_params,function(data){
$('#'+_div).html(data);
$('.editTableRow').bind('click',editfunction);
});
};
Related
I am having an issue with a pagination script that I found on the internet but can no longer find the exact one.
The issue is that clicking the previous/next or any page number on the menu does not show the next set of values, presumably the LIMIT OFFSET in my SELECT statement isn't doing as it should, but I am unsure as to why. jobs.php?action=listActiveJob&page=1&ipp (ipp being in thr paginator lcass below as 5), this show the first 5 as expected, when clicking next or page 2 for example the URL changes to jobs.php?action=listActiveJob&page=2&ipp=5 but the same 5 results are shown.
jobs.php contains a lot of code that control several pages, but here is the code that controls this list
function listActiveJob() {
$results = array();
$data = Job::getActiveList();
$results['activejobs'] = $data['results'];
$results['totalRows'] = $data['totalRows'];
require( TEMPLATE_PATH . "/job/listActiveJob.php" );
}
In anouther file(Job.php), here is the code for $data = Job::getActiveList();
public static function getActiveList() {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$pages = new Paginator;
$pages->items_total = 50;
$pages->paginate();
$sql = "SELECT SQL_CALC_FOUND_ROWS job_code, job_id, job_status, job_quoteid, job_contactid, job_companyid, job_schedulestatus, job_schedulestatus2, job_schedulestatus3
FROM jobs WHERE job_status='Active'
ORDER BY job_id DESC ".$pages->limit;
$st = $conn->prepare( $sql );
$st->execute();
$list = array();
while ( $row = $st->fetch() ) {
$job = new Job( $row );
$list[] = $job;
}
$sql = "SELECT FOUND_ROWS() AS totalRows";
$totalRows = $conn->query( $sql )->fetch();
$conn = null;
return ( array ( "results" => $list, "totalRows" => $totalRows[0] ) );
}
the list is then in listActiveJob.php and is a simple foreach
<?php foreach ( $results['activejobs'] as $job ) {
//BLA BLA LIST
}?>
here is the code at the bottom of listActiveJob.php to show and control the pagination.
<?php
$pages = new Paginator;
$pages->items_total = $results['totalRows'];
$pages->paginate();
?>
<p><?php echo $pages->display_pages();?></p>
<p><?php echo '<span class="paginationbox" style="\"margin-left:25px;\""> '. $pages->display_jump_menu() . '</span>'; ?></p>
and here is paginator.class.php
<?php
class Paginator{
var $items_per_page;
var $items_total;
var $current_page;
var $num_pages;
var $mid_range;
var $low;
var $high;
var $limit;
var $return;
var $default_ipp = 5;
function Paginator()
{
$this->current_page = 1;
$this->mid_range = 25;
$this->items_per_page = (!empty($_GET['ipp'])) ? $_GET['ipp']:$this->default_ipp;
}
function paginate()
{
if(isset($_GET['ipp'])){
if($_GET['ipp'] == 'All')
{
$this->num_pages = ceil($this->items_total/$this->default_ipp);
$this->items_per_page = $this->default_ipp;
}
else
{
if(!is_numeric($this->items_per_page) OR $this->items_per_page <= 0) $this->items_per_page = $this->default_ipp;
$this->num_pages = ceil($this->items_total/$this->items_per_page);
}
}
$this->current_page = (int) isset($_GET['page']); // must be numeric > 0
if($this->current_page < 1 Or !is_numeric($this->current_page)) $this->current_page = 1;
if($this->current_page > $this->num_pages) $this->current_page = $this->num_pages;
$prev_page = $this->current_page-1;
$next_page = $this->current_page+1;
if($this->num_pages > 10)
{
$this->return = ($this->current_page != 1 And $this->items_total >= 10) ? "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?$_GET[action]&page=$prev_page&ipp=$this->items_per_page\"> << Previous</a> ":"<span class=\"inactive\" href=\"#\"><< Previous</span> ";
$this->start_range = $this->current_page - floor($this->mid_range/2);
$this->end_range = $this->current_page + floor($this->mid_range/2);
if($this->start_range <= 0)
{
$this->end_range += abs($this->start_range)+1;
$this->start_range = 1;
}
if($this->end_range > $this->num_pages)
{
$this->start_range -= $this->end_range-$this->num_pages;
$this->end_range = $this->num_pages;
}
$this->range = range($this->start_range,$this->end_range);
for($i=1;$i<=$this->num_pages;$i++)
{
if($this->range[0] > 2 And $i == $this->range[0]) $this->return .= " ... ";
// loop through all pages. if first, last, or in range, display
if($i==1 Or $i==$this->num_pages Or in_array($i,$this->range))
{
$this->return .= ($i == $this->current_page And $_GET['page'] != 'All') ? "<a title=\"Go to page $i of $this->num_pages\" class=\"current\" href=\"#\">$i</a> ":"<a class=\"paginate\" title=\"Go to page $i of $this->num_pages\" href=\"$_SERVER[PHP_SELF]?action=$_GET[action]&page=$i&ipp=$this->items_per_page\">$i</a> ";
}
if($this->range[$this->mid_range-1] < $this->num_pages-1 And $i == $this->range[$this->mid_range-1]) $this->return .= " ... ";
}
$this->return .= (($this->current_page != $this->num_pages And $this->items_total >= 10) And ($_GET['page'] != 'All')) ? "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?action=$_GET[action]&page=$next_page&ipp=$this->items_per_page\">Next >></a>\n":"<span class=\"inactive\" href=\"#\"> >> Next</span>\n";
$this->return .= ($_GET['page'] == 'All') ? "<a class=\"current\" style=\"margin-left:10px\" href=\"#\">All</a> \n":"<a class=\"paginate\" style=\"margin-left:10px\" href=\"$_SERVER[PHP_SELF]?action=$_GET[action]&page=1&ipp=All\">All</a> \n";
}
else
{
for($i=1;$i<=$this->num_pages;$i++)
{
$this->return .= ($i == $this->current_page) ? "<a class=\"current\" href=\"#\">$i</a> ":"<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?action=$_GET[action]&page=$i&ipp=$this->items_per_page\">$i</a> ";
}
$this->return .= "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?action=$_GET[action]&page=1&ipp=All\">All</a> \n";
}
$this->low = ($this->current_page-1) * $this->items_per_page;
if(isset($_GET['ipp'])){$this->high = ($_GET['ipp'] == 'All') ? $this->items_total:($this->current_page * $this->items_per_page)-1;}
if(isset($_GET['ipp'])){$this->limit = ($_GET['ipp'] == 'All') ? "":" LIMIT $this->low,$this->items_per_page";}
}
function display_items_per_page()
{
$items = '';
$ipp_array = array(10,25,50,100,'All');
foreach($ipp_array as $ipp_opt) $items .= ($ipp_opt == $this->items_per_page) ? "<option selected value=\"$ipp_opt\">$ipp_opt</option>\n":"<option value=\"$ipp_opt\">$ipp_opt</option>\n";
return "<span class=\"paginate\">Items per page:</span><select class=\"paginate\" onchange=\"window.location='$_SERVER[PHP_SELF]?action=$_GET[action]&page=1&ipp='+this[this.selectedIndex].value;return false\">$items</select>\n";
}
function display_jump_menu()
{
for($i=1;$i<=$this->num_pages;$i++)
{
$option .= ($i==$this->current_page) ? "<option value=\"$i\" selected>$i</option>\n":"<option value=\"$i\">$i</option>\n";
}
return "<span class=\"paginate\">Page:</span><select class=\"paginate\" onchange=\"window.location='$_SERVER[PHP_SELF]?action=$_GET[action]&page='+this[this.selectedIndex].value+'&ipp=$this->items_per_page';return false\">$option</select>\n";
}
function display_pages()
{
return $this->return;
}
}
?>
I hope I have explained this well enough and greatly appreciate any help getting me in the right direction
I'm assuming that .$pages->limit in your sql statement in public static function getActiveList() adds the MySQL Limit statement to your query. However, I don't see where and how it's created in your code above. Since you're always returning the same data set, you might want to have a look there.
In my database query, it returns set of image names. I want to display them in a small size window (say 3x3), if there are more images (>9) it will populate to the next window by a tab or a specific symbol. People can click to that symbol to open the next window. I also want to recognize which image is chosen by user.
The idea of display is something like emoticon window in this image.
Do you have any idea I can make it in php ?
Here is what I am trying, please feel free to correct my code:
<?php include "dbConnector.php" ; ?>
<table>
<tr>
<?php
require_once ("paginator.php");
$pages = new Paginator; //ew paginator object to play with and initializes the default values behind the scenes
$connector= new DbConnector();
$queryObj = mysql_query("SELECT COUNT(*) FROM `mydb`.`images`");
$num_rows = mysql_num_rows($queryObj);
$pages->items_total = $num_rows; //assigns total number of records to our paginator's items_total property
$pages->mid_range = 7;//number of page links to display.
$pages->paginate();//ell the paginator to get to work and paginate
$x = mysql_query( "SELECT * FROM `mydb`.`images` ORDER BY `name` DESC $pages->limit");
$i = 0;
while($row = mysql_fetch_assoc($x))
{
$i++;
echo "<td><img src='imagefolder/".$row['name'].".png'/></td>";
if ($i % 3 == 0) {
echo '</tr><tr>';}
}
echo "Page $pages->current_page of $pages->num_pages";
echo $pages->display_pages();//displays our page numbers
?>
</tr>
<table>
The dbConnector.php as requested:
<?php
define("EW_CONN_PORT", 3306, TRUE);
define("EW_CONN_HOST", "localhost", TRUE);
define("EW_CONN_DB", "server", TRUE);
define("EW_CONN_USER", "root", TRUE);
define("EW_CONN_PASS", "admin", TRUE);
class DbConnector {
// Database connection
var $theQuery;
var $link;
function DbConnector(){
// Get the main settings from the array we just loaded
$host = 'localhost';
$db = 'mydb';
$user = 'root';
$pass = '';
// Connect to the database
$this->link = mysql_connect($host, $user, $pass);
mysql_select_db($db);
register_shutdown_function(array(&$this, 'close'));
}
//*** Function: query, Purpose: Execute a database query ***
function query($query) {
$this->theQuery = $query;
return mysql_query($query, $this->link);
}
//*** Function: fetchArray, Purpose: Get array of query results ***
function fetchArray($result) {
return mysql_fetch_array($result);
}
//*** Function: close, Purpose: Close the connection ***
function close() {
mysql_close($this->link);
}
}
?>
and paginator.php:
<?php
class Paginator{
var $items_per_page;
var $items_total;
var $current_page;
var $num_pages;
var $mid_range;
var $low;
var $high;
var $limit;
var $return;
var $default_ipp = 25;
function Paginator()
{
$this->current_page = 1;
$this->mid_range = 7;
$this->items_per_page = (!empty($_GET['ipp'])) ? $_GET['ipp']:$this->default_ipp;
}
function paginate()
{
if($_GET['ipp'] == 'All')
{
$this->num_pages = ceil($this->items_total/$this->default_ipp);
$this->items_per_page = $this->default_ipp;
}
else
{
if(!is_numeric($this->items_per_page) OR $this->items_per_page <= 0) $this->items_per_page = $this->default_ipp;
$this->num_pages = ceil($this->items_total/$this->items_per_page);
}
$this->current_page = (int) $_GET['page']; // must be numeric > 0
if($this->current_page < 1 Or !is_numeric($this->current_page)) $this->current_page = 1;
if($this->current_page > $this->num_pages) $this->current_page = $this->num_pages;
$prev_page = $this->current_page-1;
$next_page = $this->current_page+1;
if($this->num_pages > 10)
{
$this->return = ($this->current_page != 1 And $this->items_total >= 10) ? "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=$prev_page&ipp=$this->items_per_page\">« Previous</a> ":"<span class=\"inactive\" href=\"#\">« Previous</span> ";
$this->start_range = $this->current_page - floor($this->mid_range/2);
$this->end_range = $this->current_page + floor($this->mid_range/2);
if($this->start_range <= 0)
{
$this->end_range += abs($this->start_range)+1;
$this->start_range = 1;
}
if($this->end_range > $this->num_pages)
{
$this->start_range -= $this->end_range-$this->num_pages;
$this->end_range = $this->num_pages;
}
$this->range = range($this->start_range,$this->end_range);
for($i=1;$i<=$this->num_pages;$i++)
{
if($this->range[0] > 2 And $i == $this->range[0]) $this->return .= " ... ";
// loop through all pages. if first, last, or in range, display
if($i==1 Or $i==$this->num_pages Or in_array($i,$this->range))
{
$this->return .= ($i == $this->current_page And $_GET['page'] != 'All') ? "<a title=\"Go to page $i of $this->num_pages\" class=\"current\" href=\"#\">$i</a> ":"<a class=\"paginate\" title=\"Go to page $i of $this->num_pages\" href=\"$_SERVER[PHP_SELF]?page=$i&ipp=$this->items_per_page\">$i</a> ";
}
if($this->range[$this->mid_range-1] < $this->num_pages-1 And $i == $this->range[$this->mid_range-1]) $this->return .= " ... ";
}
$this->return .= (($this->current_page != $this->num_pages And $this->items_total >= 10) And ($_GET['page'] != 'All')) ? "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=$next_page&ipp=$this->items_per_page\">Next »</a>\n":"<span class=\"inactive\" href=\"#\">» Next</span>\n";
$this->return .= ($_GET['page'] == 'All') ? "<a class=\"current\" style=\"margin-left:10px\" href=\"#\">All</a> \n":"<a class=\"paginate\" style=\"margin-left:10px\" href=\"$_SERVER[PHP_SELF]?page=1&ipp=All\">All</a> \n";
}
else
{
for($i=1;$i<=$this->num_pages;$i++)
{
$this->return .= ($i == $this->current_page) ? "<a class=\"current\" href=\"#\">$i</a> ":"<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=$i&ipp=$this->items_per_page\">$i</a> ";
}
$this->return .= "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=1&ipp=All\">All</a> \n";
}
$this->low = ($this->current_page-1) * $this->items_per_page;
$this->high = ($_GET['ipp'] == 'All') ? $this->items_total:($this->current_page * $this->items_per_page)-1;
$this->limit = ($_GET['ipp'] == 'All') ? "":" LIMIT $this->low,$this->items_per_page";
}
function display_items_per_page()
{
$items = '';
$ipp_array = array(10,25,50,100,'All');
foreach($ipp_array as $ipp_opt) $items .= ($ipp_opt == $this->items_per_page) ? "<option selected value=\"$ipp_opt\">$ipp_opt</option>\n":"<option value=\"$ipp_opt\">$ipp_opt</option>\n";
return "<span class=\"paginate\">Items per page:</span><select class=\"paginate\" onchange=\"window.location='$_SERVER[PHP_SELF]?page=1&ipp='+this[this.selectedIndex].value;return false\">$items</select>\n";
}
function display_jump_menu()
{
for($i=1;$i<=$this->num_pages;$i++)
{
$option .= ($i==$this->current_page) ? "<option value=\"$i\" selected>$i</option>\n":"<option value=\"$i\">$i</option>\n";
}
return "<span class=\"paginate\">Page:</span><select class=\"paginate\" onchange=\"window.location='$_SERVER[PHP_SELF]?page='+this[this.selectedIndex].value+'&ipp=$this->items_per_page';return false\">$option</select>\n";
}
function display_pages()
{
return $this->return;
}
}
?>
Here is a modification in regards to the pagination class to remove those errors and replaced your DBConnector with my DBEngine class.
The one element you are missing is the limiting per page and next > previous links.
<?php
error_reporting(E_ALL);
class Paginator
{
var $items_per_page;
var $items_total;
var $current_page;
var $num_pages;
var $mid_range;
var $low;
var $high;
var $limit;
var $return;
var $default_ipp = 25;
function Paginator($_staticipp = '')
{
$this->current_page = (!isset($_GET['page']) || (isset($_GET['page']) && !is_numeric($_GET['page'])))? 1:$_GET['page'];
$this->mid_range = 7;
$_GET['ipp'] = (!empty($_staticipp) && is_numeric($_staticipp))? $_staticipp: $_GET['ipp'];
$this->items_per_page = (!empty($_GET['ipp']) && is_numeric($_GET['ipp'])) ? $_GET['ipp']:$this->default_ipp;
}
function paginate()
{
if(isset($_GET['ipp']) && $_GET['ipp'] == 'All') {
$this->num_pages = ceil($this->items_total/$this->default_ipp);
$this->items_per_page = $this->default_ipp;
}
else {
if(!is_numeric($this->items_per_page) || $this->items_per_page <= 0)
$this->items_per_page = $this->default_ipp;
$this->num_pages = ceil($this->items_total / $this->items_per_page);
}
$this->current_page = (isset($_GET['page']) && is_numeric($_GET['page']))? (int) $_GET['page']:0; // must be numeric > 0
if($this->current_page < 1 Or !is_numeric($this->current_page)) $this->current_page = 1;
if($this->current_page > $this->num_pages) $this->current_page = $this->num_pages;
$prev_page = $this->current_page-1;
$next_page = $this->current_page+1;
if($this->num_pages > 10) {
$this->return = ($this->current_page != 1 And $this->items_total >= 10) ? "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=$prev_page&ipp=$this->items_per_page\">« Previous</a> ":"<span class=\"inactive\" href=\"#\">« Previous</span> ";
$this->start_range = $this->current_page - floor($this->mid_range/2);
$this->end_range = $this->current_page + floor($this->mid_range/2);
if($this->start_range <= 0) {
$this->end_range += abs($this->start_range)+1;
$this->start_range = 1;
}
if($this->end_range > $this->num_pages) {
$this->start_range -= $this->end_range-$this->num_pages;
$this->end_range = $this->num_pages;
}
$this->range = range($this->start_range,$this->end_range);
for($i=1;$i<=$this->num_pages;$i++) {
if($this->range[0] > 2 And $i == $this->range[0]) $this->return .= " ... ";
// loop through all pages. if first, last, or in range, display
if($i == 1 Or $i == $this->num_pages Or in_array($i,$this->range)) {
$this->return .= ($i == $this->current_page And $_GET['page'] != 'All') ? "<a title=\"Go to page $i of $this->num_pages\" class=\"current\" href=\"#\">$i</a> ":"<a class=\"paginate\" title=\"Go to page $i of $this->num_pages\" href=\"$_SERVER[PHP_SELF]?page=$i&ipp=$this->items_per_page\">$i</a> ";
}
if($this->range[$this->mid_range-1] < $this->num_pages-1 And $i == $this->range[$this->mid_range-1]) $this->return .= " ... ";
}
$this->return .= (($this->current_page != $this->num_pages And $this->items_total >= 10) And ($_GET['page'] != 'All')) ? "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=$next_page&ipp=$this->items_per_page\">Next »</a>\n":"<span class=\"inactive\" href=\"#\">» Next</span>\n";
$this->return .= ($_GET['page'] == 'All') ? "<a class=\"current\" style=\"margin-left:10px\" href=\"#\">All</a> \n":"<a class=\"paginate\" style=\"margin-left:10px\" href=\"$_SERVER[PHP_SELF]?page=1&ipp=All\">All</a> \n";
}
else {
for($i=1;$i<=$this->num_pages;$i++) {
$this->return .= ($i == $this->current_page) ? "<a class=\"current\" href=\"#\">$i</a> ":"<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=$i&ipp=$this->items_per_page\">$i</a> ";
}
$this->return .= "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=1&ipp=All\">All</a> \n";
}
$this->low = ($this->current_page-1) * $this->items_per_page;
$this->high = (isset($_GET['ipp']) && $_GET['ipp'] == 'All') ? $this->items_total:($this->current_page * $this->items_per_page)-1;
$this->limit = (isset($_GET['ipp']) && $_GET['ipp'] == 'All') ? "":" LIMIT ".$this->low.",".$this->items_per_page;
}
function display_items_per_page()
{
$items = '';
$ipp_array = array("",9,'All');
foreach($ipp_array as $ipp_opt) $items .= ($ipp_opt == $this->items_per_page) ? "<option selected value=\"$ipp_opt\">$ipp_opt</option>\n":"<option value=\"$ipp_opt\">$ipp_opt</option>\n";
return "<span class=\"paginate\">Items per page:</span><select class=\"paginate\" onchange=\"window.location='$_SERVER[PHP_SELF]?page=1&ipp='+this[this.selectedIndex].value;return false\">$items</select>\n";
}
function display_jump_menu()
{
for($i=1;$i<=$this->num_pages;$i++) {
$option .= ($i==$this->current_page) ? "<option value=\"$i\" selected>$i</option>\n":"<option value=\"$i\">$i</option>\n";
}
return "<span class=\"paginate\">Page:</span><select class=\"paginate\" onchange=\"window.location='$_SERVER[PHP_SELF]?page='+this[this.selectedIndex].value+'&ipp=$this->items_per_page';return false\">$option</select>\n";
}
function display_pages()
{
return $this->return;
}
}
class DBEngine
{
protected $con;
// Create a default database element
public function __construct($host = '',$db = '',$user = '',$pass = '')
{
try {
$this->con = new PDO("mysql:host=$host;dbname=$db",$user,$pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
}
catch (Exception $e) {
return 0;
}
}
// Simple fetch and return method
public function Fetch($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
if($query->rowCount() > 0) {
while($array = $query->fetch(PDO::FETCH_ASSOC)) {
$rows[] = $array;
}
}
return (isset($rows) && $rows !== 0 && !empty($rows))? $rows: 0;
}
// Simple write to db method
public function Write($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
}
} ?>
<table>
<tr>
<?php
$con = new DBEngine("host","database","user","pass");
$pages = new Paginator(9);
$queryObj = $con->Fetch("SELECT COUNT(*) FROM mydb.images");
$num_rows = $queryObj[0]['COUNT(*)'];
$pages->items_total = $num_rows; //assigns total number of records to our paginator's items_total property
$pages->mid_range = 7;//number of page links to display.
$pages->paginate();//tell the paginator to get to work and paginate ?>
<tr>
<td colspan="3"><?php echo $pages->display_items_per_page(); ?></td>
</tr>
<tr>
<?php
$_sql = "SELECT * FROM mydb.images ORDER BY `name` DESC ".$pages->limit;
$x = $con->Fetch($_sql);
$i = 1;
foreach($x as $val => $row) { ?>
<td style="border:1px solid;"><img src="<?php echo $row['name']; ?>" style="max-width: 40px;" /></td>
<?php
if ($i % 3 == 0) { ?>
</tr>
<tr><?php
}
$i++;
} ?>
Page <?php echo $pages->current_page; ?> of <?php echo $pages->num_pages; ?>
<?php echo $pages->display_pages();//displays our page numbers ?>
</tr>
<table>
Trying to apply this code. It seems to count the number of records, but when you click the links to switch the page the url seems to pick up the GET variable, but nothing happens. The same 2 records from the first page stay there.
Here is the Page
<?php
require("base.php");
include_once('pagination.class.php');
$items = 2;
$page = 1;
if(isset($_GET['page']) and is_numeric($_GET['page']) and $page = $_GET['page'])
$limit = " LIMIT ".(($page-1)*$items).",$items";
else
$limit = " LIMIT $items";
$aux = Mysql_Fetch_Assoc(mysql_query("SELECT count(*) as total FROM claiminfo WHERE ( privacyset='1') "));
$query = mysql_query("SELECT *, claiminfo.claim_id AS id FROM claiminfo LEFT JOIN ( claim_pics ) ON ( claiminfo.claim_id = claim_pics.claim_id ) WHERE (
privacyset='1') && (picID IS NOT NULL) ORDER BY claiminfo.ts DESC".$limit);
if($aux['total']>0){
$p = new pagination;
$p->Items($aux['total']);
$p->limit($items);
$p->target("/gallery/");
$p->currentPage($page);
$p->calculate();
$p->changeClass("pagination");
$p->show();
while( $row = mysql_fetch_assoc( $query ) ) {
$namelocation = $row['namelocation'];
$claimholder = $row['claimholder'];
$occasion = $row['occasion'];
$geotag = $row['geotag'];
$lat = $row['lat'] ;
$lng = $row['lng'];
$claim_id = $row['id'];
$img = $row['location'];
echo "
<div class='clearfix draft product' style='margin-top: 30px;
float: left;
padding: 17px 4px 0px 20px;
margin-right: 30px;
border-style: solid;
border-color: #F092A1;
'>
<div class='photo' style='float: left;'>
<a href='/view/?claim_id=$claim_id'><img alt='' width='130' height='55' src='$img' /></a>
</div>
<div class='basic' style='float: left; margin-left: 30px;width:280px;border:1px;'>
<h3><a href='/view/?claim_id=$claim_id'>$namelocation</a></h3>
<p style='color: black;
font-family: arial;
font-size: 20px;
float: left;
'>
$occasion
</p>
</div>
<div class='stats' style='margin-top: 80px;
margin-left: 160px;'>
<div class='stat'>
<span class='unit'>
<b>$claimholder</b>
<br />
</span>
</div>
<div class='stat'>
<b>Lat:</b>
<span class='unit'>
$lat
</span>
</div>
<div class='stat'>
<b>Lng:</b>
<span class='unit'>
$lng
</span>
</div>
<br />
</div>
</div>
";
}
}else
echo"There no are records to paginate.";
?>
Here is the script
<?php
class pagination{
/*
Script Name: *Digg Style Paginator Class
Script URI: http://www.mis-algoritmos.com/2007/05/27/digg-style-pagination-class/
Description: Class in PHP that allows to use a pagination like a digg or sabrosus style.
Script Version: 0.4
Author: Victor De la Rocha
Author URI: http://www.mis-algoritmos.com
*/
/*Default values*/
var $total_pages = -1;//items
var $limit = null;
var $target = "";
var $page = 1;
var $adjacents = 2;
var $showCounter = false;
var $className = "pagination";
var $parameterName = "page";
var $urlF = false;//urlFriendly
/*Buttons next and previous*/
var $nextT = "Next";
var $nextI = "»"; //►
var $prevT = "Previous";
var $prevI = "«"; //◄
/*****/
var $calculate = false;
#Total items
function items($value){$this->total_pages = (int) $value;}
#how many items to show per page
function limit($value){$this->limit = (int) $value;}
#Page to sent the page value
function target($value){$this->target = $value;}
#Current page
function currentPage($value){$this->page = (int) $value;}
#How many adjacent pages should be shown on each side of the current page?
function adjacents($value){$this->adjacents = (int) $value;}
#show counter?
function showCounter($value=""){$this->showCounter=($value===true)?true:false;}
#to change the class name of the pagination div
function changeClass($value=""){$this->className=$value;}
function nextLabel($value){$this->nextT = $value;}
function nextIcon($value){$this->nextI = $value;}
function prevLabel($value){$this->prevT = $value;}
function prevIcon($value){$this->prevI = $value;}
#to change the class name of the pagination div
function parameterName($value=""){$this->parameterName=$value;}
#to change urlFriendly
function urlFriendly($value="%"){
if(eregi('^ *$',$value)){
$this->urlF=false;
return false;
}
$this->urlF=$value;
}
var $pagination;
function pagination(){}
function show(){
if(!$this->calculate)
if($this->calculate())
echo "<div class=\"$this->className\">$this->pagination</div>\n";
}
function getOutput(){
if(!$this->calculate)
if($this->calculate())
return "<div class=\"$this->className\">$this->pagination</div>\n";
}
function get_pagenum_link($id){
if(strpos($this->target,'?')===false)
if($this->urlF)
return str_replace($this->urlF,$id,$this->target);
else
return "$this->target?$this->parameterName=$id";
else
return "$this->target&$this->parameterName=$id";
}
function calculate(){
$this->pagination = "";
$this->calculate == true;
$error = false;
if($this->urlF and $this->urlF != '%' and strpos($this->target,$this->urlF)===false){
//Es necesario especificar el comodin para sustituir
echo "Especificaste un wildcard para sustituir, pero no existe en el target<br />";
$error = true;
}elseif($this->urlF and $this->urlF == '%' and strpos($this->target,$this->urlF)===false){
echo "Es necesario especificar en el target el comodin % para sustituir el número de página<br />";
$error = true;
}
if($this->total_pages < 0){
echo "It is necessary to specify the <strong>number of pages</strong> (\$class->items(1000))<br />";
$error = true;
}
if($this->limit == null){
echo "It is necessary to specify the <strong>limit of items</strong> to show per page (\$class->limit(10))<br />";
$error = true;
}
if($error)return false;
$n = trim($this->nextT.' '.$this->nextI);
$p = trim($this->prevI.' '.$this->prevT);
/* Setup vars for query. */
if($this->page)
$start = ($this->page - 1) * $this->limit; //first item to display on this page
else
$start = 0; //if no page var is given, set start to 0
/* Setup page vars for display. */
$prev = $this->page - 1; //previous page is page - 1
$next = $this->page + 1; //next page is page + 1
$lastpage = ceil($this->total_pages/$this->limit); //lastpage is = total pages / items per page, rounded up.
$lpm1 = $lastpage - 1; //last page minus 1
/*
Now we apply our rules and draw the pagination object.
We're actually saving the code to a variable in case we want to draw it more than once.
*/
if($lastpage > 1){
if($this->page){
//anterior button
if($this->page > 1)
$this->pagination .= "$p";
else
$this->pagination .= "<span class=\"disabled\">$p</span>";
}
//pages
if ($lastpage < 7 + ($this->adjacents * 2)){//not enough pages to bother breaking it up
for ($counter = 1; $counter <= $lastpage; $counter++){
if ($counter == $this->page)
$this->pagination .= "<span class=\"current\">$counter</span>";
else
$this->pagination .= "$counter";
}
}
elseif($lastpage > 5 + ($this->adjacents * 2)){//enough pages to hide some
//close to beginning; only hide later pages
if($this->page < 1 + ($this->adjacents * 2)){
for ($counter = 1; $counter < 4 + ($this->adjacents * 2); $counter++){
if ($counter == $this->page)
$this->pagination .= "<span class=\"current\">$counter</span>";
else
$this->pagination .= "$counter";
}
$this->pagination .= "...";
$this->pagination .= "$lpm1";
$this->pagination .= "$lastpage";
}
//in middle; hide some front and some back
elseif($lastpage - ($this->adjacents * 2) > $this->page && $this->page > ($this->adjacents * 2)){
$this->pagination .= "1";
$this->pagination .= "2";
$this->pagination .= "...";
for ($counter = $this->page - $this->adjacents; $counter <= $this->page + $this->adjacents; $counter++)
if ($counter == $this->page)
$this->pagination .= "<span class=\"current\">$counter</span>";
else
$this->pagination .= "$counter";
$this->pagination .= "...";
$this->pagination .= "$lpm1";
$this->pagination .= "$lastpage";
}
//close to end; only hide early pages
else{
$this->pagination .= "1";
$this->pagination .= "2";
$this->pagination .= "...";
for ($counter = $lastpage - (2 + ($this->adjacents * 2)); $counter <= $lastpage; $counter++)
if ($counter == $this->page)
$this->pagination .= "<span class=\"current\">$counter</span>";
else
$this->pagination .= "$counter";
}
}
if($this->page){
//siguiente button
if ($this->page < $counter - 1)
$this->pagination .= "$n";
else
$this->pagination .= "<span class=\"disabled\">$n</span>";
if($this->showCounter)$this->pagination .= "<div class=\"pagination_data\">($this->total_pages Pages)</div>";
}
}
return true;
}
}
?>
Does anyone have a hunch.
FYI: It is on a Wordpress, but this is totally a custom mysql code. I am not calling posts or anything. I was wondering that perhaps Wordpress .htaccess could be preventing it from working.
I want to add pagination to the script below which searches the database and outputs the images in a folder into rows and columns. But I want the output to be in pages, not all on the same page. How can I do it?
<?php
echo '<table border="0" cellpadding="15" cellspacing="15">';
$getImages = mysql_query("SELECT * FROM yaamembers");
if(!$getImages)
die("Cannot execute query. " . mysql_error());
$countRows = mysql_num_rows($getImages);
$i = 0;
if ($countRows > 0)
{
while ($row_rsYaamembers = mysql_fetch_assoc($getImages))
{
if ($i % 3 == 0) echo ($i > 0? '</tr>' : '') . '<tr>';
echo '<td valign="top"><a target="_blank" href="yimagelarge.php?yaaid=' . $row_rsYaamembers['yaaID'] . '"><img src="/home/youngatart/yaamembers/'.$row_rsYaamembers['photo'].'" border="0" width="120" /></td>';
if ($i == $countRows - 1)
echo '</tr>';
$i++;
}
}
echo '</table>';
?>
I have modified the code and I get three rows of three columns of images and the last row on the page filled with one image. This is the same for all the pages generated by the pagination links. Its supposed to fill up evenly before going to the next page. What could i be doing wrong?
Modified code below:
<?Php
$getImages = mysql_query("SELECT * FROM yaamembers");
if(!$getImages)
die("Cannot execute query. " . mysql_error());
$output = "";
$getImages = get_images($start,$limit);
if ($getImages && mysql_num_rows($getImages) > 0)
{
/* Pagination section2 */
$getAllImages = get_images();
$total_items = mysql_num_rows($getAllImages);
$paginate = paginate($targetpage,$total_items,$limit,$pagenum);
$paginate = trim($paginate);
/* Pagination section2 End */
echo '<table border="0" cellpadding="15" cellspacing="15">';
$countRows = mysql_num_rows($getImages);
$i = 0;
if ($countRows > 0)
{
while ($row_rsYaamembers = mysql_fetch_assoc($getImages))
{
if ($i % 3 == 0) echo ($i > 0) . '<tr>';
echo '<td valign="top"><a target="_blank" href="yimagelarge.php?yaaid=' . $row_rsYaamembers['yaaID'] . '"><img src="http://localhost/youngatart/yaamembers/'.$row_rsYaamembers['photo'].'" border="0" width="120" /></a><div id="text2"><div class="clear_4"></div><div align="center" id="text2"><a target="_blank" href="yimagelarge.php?yaaid=' . $row_rsYaamembers['yaaID'] . '"><div align="center" id="text2"> '.$row_rsYaamembers['school'].'</a></div><div class="clear_4"></div><div align="center" id="text2"><a target="_blank" href="yimagelarge.php?yaaid=' . $row_rsYaamembers['yaaID'] . '"> '.$row_rsYaamembers['year'].'</a></div></div></td>';
if ($i == $countRows - 1)
echo '</tr>';
$i++;
}
}
echo '</table>';
$output .= $paginate;
}
echo $output;
?>
I suggest a simple change in your script, to make it comfortable for my explanations (because I'm not a good programmer! :) ). Also, I have created some functions to work with.
Suggested changes
Make some changes in HTML (use div and put a CSS class, and play
with CSS)
Make the get_images as a function
How to use
function get_images($start=0,$limit=0)
{
mysql_connect("host","user","pass")or die("Cannot connect DB");
mysql_select_db("db_name")or die("DB does not exist");
$sql = "SELECT * FROM yaamembers";
if($start!=0 || $limit!=0)
{
$sql .= " LIMIT ". $start .", ". $limit;
}
$sql .= ";";
$data = mysql_query($sql);
mysql_close();
return $data;
}
/* Pagination section1 */
$pagenum = 1;
$limit = 10; /* Items per page*/
$start = 0;
if(isset($_GET['pagenum'])) {
$pagenum = $_GET['pagenum'];
}
$url = get_current_url();
$targetpage = format_url($url, "pagenum");
if($pagenum)
{
$start = ($pagenum - 1) * $limit;
}
/* Pagination section1 End */
$output = "";
$getImages = get_images($start,$limit)
if ($getImages && mysql_num_rows($getImages) > 0)
{
/* Pagination section2 */
$getAllImages = get_images();
$total_items = mysql_num_rows($getAllImages);
$paginate = paginate($targetpage,$total_items,$limit,$pagenum);
$paginate = trim($paginate);
/* Pagination section2 End */
while ($row_rsYaamembers = mysql_fetch_assoc($getImages))
{
$output .= "
<div>
<a target="_blank" href="yimagelarge.php?yaaid=' . $row_rsYaamembers['yaaID'] . '">
<img src="/home/youngatart/yaamembers/'.$row_rsYaamembers['photo'].'" border="0" width="120" />
</a>
</div>";
}
$output .= $paginate;
}
echo $output;
Here follows the functions to paginate
<?php
function paginate($targetpage,$total_items=0,$limit=10,$pagenum=1)
{
/*
* Remember to remove pagenum variable from $targetpage variable
*/
$adjacents = 3; /* How many items adjascent to page link */
/* How many items to show per page $limit = 30; */
/* Setup page vars for display. */
if ($pagenum == 0)
$pagenum = 1; /* If no page var is given, default to 1. */
$prev = $pagenum - 1; /* Previous page is page - 1 */
$next = $pagenum + 1; /* Next page is page + 1 */
$lastpage = ceil($total_items/$limit); /* Last page is equal to total pages / items per page, rounded up. */
$lpm1 = $lastpage - 1; /* Last page minus 1 */
/*
Now we apply our rules and draw the pagination object.
We're actually saving the code to a variable in case we want to draw it more than once.
*/
$pagination = "";
if($lastpage > 1)
{
$pagination .= "<div class=\"pagination\">";
/* previous button */
if ($pagenum > 1)
{
$pagination .= "Previous";
}
else
{
$pagination .= "<span class=\"disabled\">Previous</span>";
}
/* Pages */
if ($lastpage < 7 + ($adjacents * 2)) /* Not enough pages to bother breaking it up. */
{
for ($counter = 1; $counter <= $lastpage; $counter++)
{
if ($counter == $pagenum)
{
$pagination .= "<span class=\"current\">$counter</span>";
}
else
{
$pagination .= "$counter";
}
}
}
elseif($lastpage > 5 + ($adjacents * 2)) /* Enough pages to hide some */
{
/* Close to beginning; only hide later pages */
if($pagenum < 1 + ($adjacents * 2))
{
for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
{
if ($counter == $pagenum)
{
$pagination .= "<span class=\"current\">$counter</span>";
}
else
{
$pagination .= "$counter";
}
}
$pagination .= "...";
$pagination .= "$lpm1";
$pagination .= "$lastpage";
}
/* In middle; hide some front and some back */
elseif($lastpage - ($adjacents * 2) > $pagenum && $pagenum > ($adjacents * 2))
{
$pagination .= "1";
$pagination .= "2";
$pagination .= "...";
for ($counter = $pagenum - $adjacents; $counter <= $pagenum + $adjacents; $counter++)
{
if ($counter == $pagenum)
{
$pagination .= "<span class=\"current\">$counter</span>";
}
else
{
$pagination .= "$counter";
}
}
$pagination .= "...";
$pagination .= "$lpm1";
$pagination .= "$lastpage";
}
/* close to end; only hide early pages */
else
{
$pagination .= "1";
$pagination .= "2";
$pagination .= "...";
for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
{
if ($counter == $pagenum)
{
$pagination .= "<span class=\"current\">$counter</span>";
}
else
{
$pagination .= "$counter";
}
}
}
}
/* Next button */
if ($pagenum < $counter - 1)
{
$pagination .= "next";
}
else
{
$pagination .= "<span class=\"disabled\">next</span>";
}
$pagination .= "</div>\n";
}
return $pagination;
}
function format_url($url, $fileds)
{
/*-To remove queries from URL, the field input may be single string or an array of strings. */
$url_filed_array = explode("&",$url);
$return_url = '';
for($i=0; $i<count($url_filed_array); $i++)
{
if(is_array($fileds))
{
if($i==0)
{
$_url = explode('?',$url_filed_array[$i]);
$return_url .=$_url[0] .'?';
$url_filed = explode('=',$_url[1]);
}
else
{
$url_filed = explode('=',$url_filed_array[$i]);
}
if(!in_array($url_filed[0],$fileds))
{
if($i==0 && isset($_url[1]))
{
$return_url .=$_url[1];
}
else
{
$return_url .=$url_filed_array[$i];
}
if(($i+1) != count($url_filed_array))
{
$return_url .="&";
}
}
}
else
{
if($i==0)
{
$_url = explode('?',$url_filed_array[$i]);
$return_url .=$_url[0] .'?';
$url_filed = explode('=',$_url[1]);
}
else
{
$url_filed = explode('=',$url_filed_array[$i]);
}
if($url_filed[0]!=$fileds)
{
if($i==0 && isset($_url[1]))
{
$return_url .=$_url[1];
}
else
{
$return_url .=$url_filed_array[$i];
}
if(($i+1) != count($url_filed_array))
{
$return_url .="&";
}
}
}
}
if(substr($return_url,-1)=='&')
{
$return_url = substr($return_url, 0, -1);
}
if(substr($return_url,-1)=='?')
{
$return_url = substr($return_url, 0, -1);
}
return $return_url;
}
function get_current_url()
{
$pageURL = (#$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
if ($_SERVER["SERVER_PORT"] != "80")
{
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
}
else
{
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
?>
CSS code
div.pagination {
padding:3px;
margin:3px;
text-align:center;
}
div.pagination span.disabled ,
div.pagination span.current ,
div.pagination a
{
background:url('../images/pagination_bg.jpg') #ffffff repeat-x right center;
height: 28px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
padding: 5px 8px;
margin-right: 8px;
color: #6B6868;
}
div.pagination a {
border: 1px solid #ddd;
text-decoration: none;
}
div.pagination a:hover, div.pagination a:active {
border:1px solid #f2813a;
color: #f2813a;
background-color: #F46F1B;
}
div.pagination span.current {
border: 1px solid #f2813a;
font-weight: bold;
color: #FFF;
background:url('../images/pagination_bg_active.jpg') #F46F1B repeat-x right center;
}
div.pagination span.disabled {
border: 1px solid #f3f3f3;
color: #ccc;
}
div.pagination span.current,
div.pagination span.disabled {
cursor: default;
}
Create two background images as you like, in folder images:
pagination_bg.jpg /* Normal button image */
pagination_bg_active.jpg /* Active or current page button image */
I am working on a PHP-Mysql based website which has some large lists to display(for example product lists).Now I had to break it down to pages for the convenience of the user.So I have added pagination using PHP.Now this does a page refresh each time I click on the page number.So I have a base with PHP/MySQL and want to add Ajax/jquery to it for avoiding unnecessary page refresh.How can I add pagination to the existing code that I have??
Here is the php code for reference.
<div class="flt width710">
<div style="margin-top:10px;" class="flt mapnewalert"> <?php //echo ucfirst($_SESSION['$city']) ?></div>
<div style="float:right" id="toppagesel">
<?php
echo $pages->display_pages();
echo $pages->display_items_per_page();
//echo "<span class=\"\">".$pages->display_jump_menu()."</span>";
$query = "SELECT * from properties,locality,cities where properties.city_id='".$_SESSION['$cityId']."' and properties.locality_id=locality.locality_id and properties.city_id=cities.city_id $pages->limit";
$result = mysql_query($query) or die(mysql_error());
//$getProperty = $propertyDetails->getPropertyDetailsByCityIdPaginate($_SESSION['$cityId'],$limit);
?>
<?php //echo $pages->display_pages(); ?><?php //echo $pages->display_items_per_page();?>
</div>
</div>
And the pagination class:
class Paginator{
var $items_per_page;
var $items_total;
var $current_page;
var $num_pages;
var $mid_range;
var $low;
var $limit;
var $return;
var $default_ipp;
var $querystring;
var $ipp_array;
function Paginator()
{
$this->current_page = 1;
$this->mid_range = 2;
$this->ipp_array = array(2,4,6,8,'All');
$this->items_per_page = (!empty($_GET['ipp'])) ? $_GET['ipp']:$this->default_ipp;
}
function paginate()
{
if(!isset($this->default_ipp)) $this->default_ipp=2;
if($_GET['ipp'] == 'All')
{
$this->num_pages = 1;
// $this->items_per_page = $this->default_ipp;
}
else
{
if(!is_numeric($this->items_per_page) OR $this->items_per_page <= 0) $this->items_per_page = $this->default_ipp;
$this->num_pages = ceil($this->items_total/$this->items_per_page);
}
$this->current_page = (isset($_GET['page'])) ? (int) $_GET['page'] : 1 ; // must be numeric > 0
$prev_page = $this->current_page-1;
$next_page = $this->current_page+1;
if($_GET)
{
$args = explode("&",$_SERVER['QUERY_STRING']);
foreach($args as $arg)
{
$keyval = explode("=",$arg);
if($keyval[0] != "page" And $keyval[0] != "ipp") $this->querystring .= "&" . $arg;
}
}
if($_POST)
{
foreach($_POST as $key=>$val)
{
if($key != "page" And $key != "ipp") $this->querystring .= "&$key=$val";
}
}
if($this->num_pages > 4)
{
$this->return = ($this->current_page > 1 And $this->items_total >= 10) ? "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=$prev_page&ipp=$this->items_per_page$this->querystring\">« Previous</a> ":"<span class=\"inactive\" href=\"#\">« Previous</span> ";
$this->start_range = $this->current_page - floor($this->mid_range/2);
$this->end_range = $this->current_page + floor($this->mid_range/2);
if($this->start_range <= 0)
{
$this->end_range += abs($this->start_range)+1;
$this->start_range = 1;
}
if($this->end_range > $this->num_pages)
{
$this->start_range -= $this->end_range-$this->num_pages;
$this->end_range = $this->num_pages;
}
$this->range = range($this->start_range,$this->end_range);
for($i=1;$i<=$this->num_pages;$i++)
{
if($this->range[0] > 2 And $i == $this->range[0]) $this->return .= " ... ";
// loop through all pages. if first, last, or in range, display
if($i==1 Or $i==$this->num_pages Or in_array($i,$this->range))
{
$this->return .= ($i == $this->current_page And $_GET['page'] != 'All') ? "<a title=\"Go to page $i of $this->num_pages\" class=\"current\" href=\"#\">$i</a> ":"<a class=\"paginate\" title=\"Go to page $i of $this->num_pages\" href=\"$_SERVER[PHP_SELF]?page=$i&ipp=$this->items_per_page$this->querystring\">$i</a> ";
}
if($this->range[$this->mid_range-1] < $this->num_pages-1 And $i == $this->range[$this->mid_range-1]) $this->return .= " ... ";
}
$this->return .= (($this->current_page < $this->num_pages And $this->items_total >= 10) And ($_GET['page'] != 'All') And $this->current_page > 0) ? "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=$next_page&ipp=$this->items_per_page$this->querystring\">Next »</a>\n":"<span class=\"inactive\" href=\"#\">» Next</span>\n";
$this->return .= ($_GET['page'] == 'All') ? "<a class=\"current\" style=\"margin-left:10px\" href=\"#\">All</a> \n":"<a class=\"paginate\" style=\"margin-left:10px\" href=\"$_SERVER[PHP_SELF]?page=1&ipp=All$this->querystring\">All</a> \n";
}
else
{
for($i=1;$i<=$this->num_pages;$i++)
{
$this->return .= ($i == $this->current_page) ? "<a class=\"current\" href=\"#\">$i</a> ":"<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=$i&ipp=$this->items_per_page$this->querystring\">$i</a> ";
}
$this->return .= "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=1&ipp=All$this->querystring\">All</a> \n";
}
$this->low = ($this->current_page <= 0) ? 0:($this->current_page-1) * $this->items_per_page;
if($this->current_page <= 0) $this->items_per_page = 0;
$this->limit = ($_GET['ipp'] == 'All') ? "":" LIMIT $this->low,$this->items_per_page";
}
}
How can I achieve it??I referred other threads and tried but couldn't get it working in my context.I am a newbie to ajax jquery part so sorry if its a easy task!! :P
PS: Is this possible in the current scenario or do I have to make the changes to my pagination class and php code.Please throw some light on it!!
Thanks
There are many JavaScript pagination library will help you to simplify your work,
can you try this pagination library,
Demo: http://www.frequency-decoder.com/demo/table-sort-revisited/paginate/
Website: http://www.frequency-decoder.com/2007/10/19/client-side-table-pagination-script/
$(document).ready(function()
{
$('.paginate').live('click', function(e)
{
e.preventDefault();
var btnPage = $(this);
$.ajax(
{
url : btnPage.attr('href'),
success : function(resp)
{
// replace current results with new results.
$('#project_section').html(resp);
},
error : function()
{
window.location.href = btnPage.attr('href');
}
});
});
});
Here $(".paginate") is the class of the <li> in my paginator class.
I got the answer here
Thanks