Duplicating a class - php

I am currently using a pagination script that uses a class named "pagination". I would like to duplicate this class in another file to use it again. I'm having problems with my framework recognizing it as "duplicate". I know that changing it should be as simple as changing the class name, but there are several functions within the class that makes it too complex for me to figure out.
So my question is, based on the code below, what variables, functions, values, etc. would I need to change in my class in order to create an identical copy of it?
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 = "pg";
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;
}
}
?>

Try to include the file which holds the pagination class only once!
Use incldue_once or require_once instead of include and require.

Related

php jquery pagination expanding without moving to the next page

Im working on a codeigniter project which takes results and adds it to the page with pagination.
The problem that im having is,
the page shows all the page numbers but the first page always seems empty. When i move to the second page it shows the first page results along with the second page results. Even if i move to the first page again its empty.
when i move further, all the results seems to be stacked rather than paginating.
so first page 0 results. the second page shows 30, 3rd page shows 45 results.
below is my script
<script type="text/javascript">
$(document).ready(function(){
function loading_show(){
$('#loading').html("<img src='<?php echo $url?>images/loading.gif'/>").fadeIn('fast');
}
function loading_hide(){
$('#loading').fadeOut('fast');
}
function loadData(page){
loading_show();
$.ajax
({
type: "POST",
url: "<?php echo base_url()?>index.php/controls/ajaxload",
data: "page="+page,
success: function(msg)
{
$("#container").ajaxComplete(function(event, request, settings)
{
loading_hide();
$("#container").html(msg);
});
}
});
}
loadData(1);
$('#container .pagination li.active').live('click',function(){
var page = $(this).attr('p');
loadData(page);
});
$('#go_btn').live('click',function(){
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(page);
}else{
alert('Enter Number '+no_of_pages);
$('.goto').val("").focus();
return false;
}
});
});
</script>
php code
function ajaxload()
{
if($_POST['page'])
{
$page = $_POST['page'];
$cur_page = $page;
$page -= 1;
$per_page = 15;
$previous_btn = true;
$next_btn = true;
$first_btn = true;
$last_btn = true;
$start = $page * $per_page;
$city ='London';
$this->load->model('control_model');
$query_pag_datas = $this->control_model->data_for_pagination($start, $per_page,$city);
$msg = "";
foreach ($query_pag_datas as $single):
$htmlmsg = htmlentities($single['Description']);
$msg .= "<li><b>" . $single['offID'] . "</b> " . $htmlmsg . "</li>";
endforeach;
$msg = "<div class='data'><ul>" . $msg . "</ul></div>";
$count = $this->control_model->count_pages($city);
$no_of_paginations = ceil($count / $per_page);
if ($cur_page >= 7) {
$start_loop = $cur_page - 3;
if ($no_of_paginations > $cur_page + 3)
$end_loop = $cur_page + 3;
else if ($cur_page <= $no_of_paginations && $cur_page > $no_of_paginations - 6) {
$start_loop = $no_of_paginations - 6;
$end_loop = $no_of_paginations;
} else {
$end_loop = $no_of_paginations;
}
} else {
$start_loop = 1;
if ($no_of_paginations > 7)
$end_loop = 7;
else
$end_loop = $no_of_paginations;
}
$msg .= "<div class='pagination'><ul>";
if ($first_btn && $cur_page > 1) {
$msg .= "<li p='1' class='active'>First</li>";
} else if ($first_btn) {
$msg .= "<li p='1' class='inactive'>First</li>";
}
if ($previous_btn && $cur_page > 1) {
$pre = $cur_page - 1;
$msg .= "<li p='$pre' class='active'>Previous</li>";
} else if ($previous_btn) {
$msg .= "<li class='inactive'>Previous</li>";
}
for ($i = $start_loop; $i <= $end_loop; $i++) {
if ($cur_page == $i)
$msg .= "<li p='$i' style='color:#fff;background-color:#006699;' class='active'>{$i}</li>";
else
$msg .= "<li p='$i' class='active'>{$i}</li>";
}
if ($next_btn && $cur_page < $no_of_paginations) {
$nex = $cur_page + 1;
$msg .= "<li p='$nex' class='active'>Next</li>";
} else if ($next_btn) {
$msg .= "<li class='inactive'>Next</li>";
}
if ($last_btn && $cur_page < $no_of_paginations) {
$msg .= "<li p='$no_of_paginations' class='active'>Last</li>";
} else if ($last_btn) {
$msg .= "<li p='$no_of_paginations' class='inactive'>Last</li>";
}
$goto = "<input type='text' class='goto' size='1' style='margin-top:-1px;margin-left:60px;'/><input type='button' id='go_btn' class='go_button' value='Go'/>";
$total_string = "<span class='total' a='$no_of_paginations'>Page <b>" . $cur_page . "</b> of <b>$no_of_paginations</b></span>";
$msg = $msg . "</ul>" . $goto . $total_string . "</div>";
echo $msg;
}
}
any help will be appreciated.
So if the page you are posting is 1, this is what you get:
Page 1:
$page = $_POST['page'];//let's say we're posting page 1, so $page === 1
...
$page -= 1;//so now, page === 0
...
$start = $page * $per_page;//which, since math, will be 0
...
$query_pag_datas = $this->control_model->data_for_pagination($start, $per_page,$city);
// you just called data_for_pagination(0, 15, 'London')
Since we can't see the data_for_pagination method, I'm going to assume that this first parameter is the number of results you are requesting. This makes sense because as the page number increases, the number of results will increase:
Page 2:
$page = $_POST['page'];//let's say we're posting page 2, so $page === 2
...
$page -= 1;//so now, page === 1
...
$start = $page * $per_page;//which, since math, will be 15
...
$query_pag_datas = $this->control_model->data_for_pagination($start, $per_page,$city);
// you just called data_for_pagination(15, 15, 'London')
Page 3:
$page = $_POST['page'];//let's say we're posting page 3, so $page === 3
...
$page -= 1;//so now, page === 2
...
$start = $page * $per_page;//which, since math, will be 30
...
$query_pag_datas = $this->control_model->data_for_pagination($start, $per_page,$city);
// you just called data_for_pagination(30, 15, 'London')
Hope that helps.
change
$page -= 1;
to
$page = ($page > 0 ) ? $page -1 : 0 ;
in the first click page is 0
so
0-1 => -1
-1 * 15 => -15 ;
your first offset is -15 !

Pagination works in counting and dividing, but links don't change records

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.

Pagination in HTML code embeded in PHP

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 */

pagination class not showing correct amt of pages

the problem with the class is that if i want to display 30 records at a time and i have 60 total records the pagination divs that shows the page numbers only shows page #1 and not page #2. i have tried to figure out how to fix it but i have given up. any help would greatly be apreciated.
this is how i call attributes to the class.
$paginate = new Pagination;
$paginate->pageName = "index.php"; //sets the page to use
$paginate->perPage = 10; //show num of records per page
$paginate->adjacents = 3; //current page adjacent to
$paginate->sql = "select * from tbl_products"; //the main query
$query = $db->query($paginate->getData());
while($row = mysql_fetch_object($query)) {
print $row->pName."<br/>";
}
$paginate->showPagination(); //shows the pagination div
here is the class.
<?php
include_once("class.db.php");
class Pagination
{
var $param;
var $perPage;
var $adjacents;
var $start;
var $sql;
var $pageName;
function __construct()
{
$this->db = new MysqlDB;
$this->db->connect();
}
function setParam()
{
if(isset($_GET['page']) && is_numeric($_GET['page']) && ($_GET['page'] > 0))
{
$this->param = $_GET['page'];
}
else
{
$this->param = 1;
}
}
function setIndex()
{
$this->setParam();
return $this->start = ($this->param * $this->perPage) - $this->perPage;
}
function showPagination($param1=null,$param2=null,$param3=null)
{
$qRows = $this->db->query($this->sql);
$numRows = $this->db->num_rows($qRows);
$numOfPages = ceil($numRows / $this->perPage);
$param = $this->param;
$pageName = $this->pageName;
$string = "";
//set pagination parameters.
if($param1 != null)
{
if(isset($_GET[$param1]))
{
$param1Value = $_GET[$param1];
$string .= "&".$param1."=".$param1Value;
}
}
if($param2 != null)
{
if(isset($_GET[$param2]))
{
$param2Value = $_GET[$param2];
$string .= "&".$param2."=".$param2Value;
}
}
if($param3 != null)
{
if(isset($_GET[$param3]))
{
$param3Value = $_GET[$param3];
$string .= "&".$param3."=".$param3Value;
}
}
print "<div class='pagination'>";
print "<a href='$this->pageName?page=1$string' class='previous-off'> First </a>";
// ----------------------------------------------------------------------------
// PRINT ALL PAGES TO THE LEFT //
if(($param - $this->adjacents) > 1)
{
print "<span>...</span>";
$lowerLimit = $param - $this->adjacents;
//print all on left side.
for($i = $lowerLimit; $i< $param; $i++)
{
print "<a href='$pageName?page=$param = $i$string'> $i </a>";
}
}
else
{
//print all numbers between current page and first page.
for($i = 1; $i < $param; $i++)
{
print "<a href='$pageName?page=$i$string'> $i </a>";
}
}
// ----------------------------------------------------------------------------
//print current page
if(($param != 0) && ($param != $numOfPages))
{
print "<span class='current'>$param</span>";
}
// ----------------------------------------------------------------------------
//PRINT ALL PAGES TO THE RIGHT
if(($param + $this->adjacents) < $numOfPages)
{
$upperLimit = $param + $this->adjacents;
for($i=($param + 1); $i<=$upperLimit; $i++)
{
print "<a href='$pageName?page=$i$string'> $i </a>";
}
print "<span>...</span>";
}
else
{
//print all page numbers if out of padded range
for($i = ($param + 1); $i<$numOfPages; $i++ )
{
print "<a href='$pageName?page=$i$string'> $i </a>";
}
}
// ----------------------------------------------------------------------------
$lastPage = $numOfPages - 1;
print "<a class='next' href='$pageName?page=$lastPage$string'> Last </li>";
print "</div>";
}
function getData()
{
$query = $this->sql;
$this->start = $this->setIndex();
return "$query LIMIT $this->start, $this->perPage";
}
function errors()
{
$query = $this->sql;
print "$query LIMIT $this->start, $this->perPage"."<br/>";
print "this->start ".$this->start."<br/>";
print "this->param ".$this->param."<br/>";
print "this->perPage ".$this->perPage."<br/>";
print "this->setindex() ".$this->setIndex()."<br/>";
}
}
?>
Personally I tend to stray from SELECT * FROM tbl type queries as if you have a large table, it can be slow. Therefore, I run two queries: one to get the total number of records, and one to get the data set I need based on a paging parameter in the URL, e.g. example.com/news.php?page=2.
From there, I can instantiate my own paging class, which is pretty simple:
<?php
class Paging {
private $total;
private $batch;
private $page;
private $prefix;
public function __construct($total=0, $batch=10, $page=1, $url="") {
$this->total = intval($total);
$this->batch = intval($batch);
$this->page = intval($page);
$this->url = $url;
}
public function total_pages() {
return ceil($this->total/$this->batch);
}
public function render() {
$html = "";
// only display paging if we have more than the batch value
if ($this->total > $this->batch) {
$html.= '<p>Go to page:';
for ($i=1; $i <= $this->total_pages()) {
if ($i==$this->page) {
$html.= ' <span class="current">'.$i.'</span>';
}
else {
$html.= ' '.$i.'';
}
}
$html.= '</p>';
}
return $html;
}
}
Then to use:
<?php
// get total number of records
$sql = "SELECT COUNT(*) AS total FROM tbl";
$res = $db->query($sql);
$row = $res->fetch();
$total = $row['total'];
$batch = 20;
$page = intval($_GET['page']);
// instantiate paging class
require_once('paging.class.php');
$paging = new Paging($total, $batch, $page, "mypage.php?page=%s");
// do normal page stuff here...
// render the pagination links
echo $paging->render();
Feel free to use the above code and modify to your needs

Pagination Class calculates incorrectly

ive written a pagination class and it looks like its not outputting the correct amount of rows. i have a table full of 51 records and instead it shows only 30 records and as for the pages it shows only page 1 where it should show page 1 and 2. the pages are viewed by going to page=1 as a browser param. when i try to view page=2 i see the rest of the records. here is the class.
include_once("class.db.php");
class Pagination {
var $param;
var $perPage;
var $adjacents;
var $start;
var $sql;
var $pageName;
function __construct() {
$this->db = new MysqlDB;
$this->db->connect();
}
function setParam() {
if(isset($_GET['page']) && is_numeric($_GET['page']) && ($_GET['page'] > 0)) {
$this->param = $_GET['page'];
} else {
$this->param = 1;
}
}
function setIndex() {
$this->setParam();
return $this->start = ($this->param * $this->perPage) - $this->perPage;
}
function showPagination() {
$qRows = $this->db->query($this->sql);
$numRows = $this->db->num_rows($qRows);
$numOfPages = ceil($numRows / $this->perPage);
$param = $this->param;
$pageName = $this->pageName;
print "<div class='pagination'>";
print "<a href='$this->pageName?page=1' class='previous-off'> First </a>";
// ----------------------------------------------------------------------------
// PRINT ALL PAGES TO THE LEFT //
if(($param - $this->adjacents) > 1) {
print "<span>...</span>";
$lowerLimit = $param - $this->adjacents;
//print all on left side.
for($i = $lowerLimit; $i< $param; $i++) {
print "<a href='$pageName?page=$param = $i'> $i </a>";
}
} else {
//print all numbers between current page and first page.
for($i = 1; $i < $param; $i++) {
print "<a href='$pageName?page=$i'> $i </a>";
}
}
// ----------------------------------------------------------------------------
//print current page
if(($param != 0) && ($param != $numOfPages)) {
print "<span class='current'>$param</span>";
}
// ----------------------------------------------------------------------------
//PRINT ALL PAGES TO THE RIGHT
if(($param + $this->adjacents) < $numOfPages) {
$upperLimit = $param + $this->adjacents;
for($i=($param + 1); $i<=$upperLimit; $i++) {
print "<a href='$pageName?page=$i'> $i </a>";
}
print "<span>...</span>";
} else {
//print all page numbers if out of padded range
for($i = $param + 1; $i<$numOfPages; $i++ ) {
print "<a href='$pageName?page=$i'> $i </a>";
}
}
// ----------------------------------------------------------------------------
$lastPage = $numOfPages - 1;
print "<a class='next' href='$pageName?page=$lastPage'> Last </li>";
print "</div>";
}
function getData() {
$query = $this->sql;
$this->start = $this->setIndex();
return "$query LIMIT $this->start, $this->perPage";
}
}
this is how i use the class:
$db = new MysqlDB;
$paginate = new Pagination;
$paginate->pageName = "index.php"; //sets the page to use
$paginate->perPage = 10; //show num of records per page
$paginate->adjacents = 3; //current page adjacent to
$paginate->sql = "select * from tbl_products"; //the main query
$query = $db->query($paginate->getData());
while($row = mysql_fetch_object($query)) {
print $row->pName."<br/>";
}
$paginate->showPagination(); //shows the pagination div
In function setIndex you have to write:
return $this->start = (($this->param - 1) * $this->perPage) - $this->perPage;
because a query should look like:
for page 1: SELECT ... LIMIT 0,[nr_of_pages]
for page 2: SELECT ... LIMIT [nr_of_pages]*1,[nr_of_pages]
...

Categories