Pagination in HTML code embeded in PHP - 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 */

Related

Limit Pagination Numbers For Huge Databases

I can't seem to find the answer anyway so guess I need to ask at least I did try google anyway I am making a group feature similar to the one facebook has got but not as good since i'm the only one developing this but over time it get better.
Anyway,
how can I make this code limit the pagination numbers? for example if there is loads of results in the database I only want to first 10 to be displayed after that use dots so they can click and go more in depth if they want to so when the click the dot they get another 10 results so 20-30 will then be displayed as pagination. I don't need it exactly like this but some way to limit the ammount of numbers being displayed at a time.
Here;s the code
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">
#content
{
width: 900px;
margin: 0 auto;
font-family:Arial, Helvetica, sans-serif;
}
.page
{
float: right;
margin: 0;
padding: 0;
}
.page li
{
list-style: none;
display:inline-block;
}
.page li a, .current
{
display: block;
padding: 5px;
text-decoration: none;
color: #8A8A8A;
}
.current
{
font-weight:bold;
color: #000;
}
.button
{
padding: 5px 15px;
text-decoration: none;
background: #333;
color: #F3F3F3;
font-size: 13PX;
border-radius: 2PX;
margin: 0 4PX;
display: block;
float: left;
}
</style>
</head>
<body>
<div id="content">
<?php
error_reporting(0);
$query1=mysql_connect("localhost","root","");
mysql_select_db("freeze_demo",$query1);
error_reporting(0);
$start=0;
$limit=1;
if(isset($_GET['id']))
{
$id=$_GET['id'];
$start=($id-1)*$limit;
}
$query=mysql_query("select * from pagination LIMIT $start, $limit");
echo "<ul>";
while($query2=mysql_fetch_array($query))
{
echo "<li>".$query2['text1']."</li>";
}
echo "</ul>";
$rows=mysql_num_rows(mysql_query("select * from pagination"));
$total=ceil($rows/$limit);
if($id>1)
{
echo "<a href='?id=".($id-1)."' class='button'>PREVIOUS</a>";
}
if($id!=$total)
{
echo "<a href='?id=".($id+1)."' class='button'>NEXT</a>";
}
echo "<ul class='page'>";
for($i=1;$i<=$total;$i++)
{
if($i==$id) { echo "<li class='current'>".$i."</li>"; }
else { echo "<li><a href='?id=".$i."'>".$i."</a></li>"; }
}
echo "</ul>";
?>
</div>
</body>
</html>
Just basically need to update it for the future when my database or a certain group gets bigger.
Thanks
<?php
function custom_pagination($page, $totalpage, $link, $show) //$link = '&page=%s'
{
//show page
if($totalpage == 0)
{
return 'Page 0 of 0';
} else {
$nav_page = '<div class="navpage"><span class="current">Page '.$page.' of '.$totalpage.': </span>';
$limit_nav = 3;
$start = ($page - $limit_nav <= 0) ? 1 : $page - $limit_nav;
$end = $page + $limit_nav > $totalpage ? $totalpage : $page + $limit_nav;
if($page + $limit_nav >= $totalpage && $totalpage > $limit_nav * 2){
$start = $totalpage - $limit_nav * 2;
}
if($start != 1){ //show first page
$nav_page .= '<span class="item"> [1] </span>';
}
if($start > 2){ //add ...
$nav_page .= '<span class="current">...</span>';
}
if($page > 5){ //add prev
$nav_page .= '<span class="item">«</span>';
}
for($i = $start; $i <= $end; $i++){
if($page == $i)
$nav_page .= '<span class="current">'.$i.'</span>';
else
$nav_page .= '<span class="item"> ['.$i.'] </span>';
}
if($page + 3 < $totalpage){ //add next
$nav_page .= '<span class="item">»</span>';
}
if($end + 1 < $totalpage){ //add ...
$nav_page .= '<span class="current">...</span>';
}
if($end != $totalpage) //show last page
$nav_page .= '<span class="item"> ['.$totalpage.'] </span>';
$nav_page .= '</div>';
return $nav_page;
}
}
//using
if(isset($_GET['page'])) {
$page = $_GET['page'];
} else {
$page = 1;
}
$sql = "SELECT count(*) AS total FROM post ORDER BY idpost DESC"; //please select COUNT is fast
$result = mysql_query($sql);
$rows = mysql_fetch_array($result);
$show = 5; //Show 5 result per page
$totalpage = ceil($rows['total'] / $show); //Total page
$start = ($page * $show) - $show; //Start result
$yourQuery = "SELECT * FROM post ORDER BY id LIMIT $start, $show";
//Query and show here
//Show pagination
echo custom_pagination($page, $totalpage, 'index.php?action=detail&page=%s', $show);
?>
Given that $id is a page number (perhaps refactor this to be $page so it it recognised as a page number, rather an a unique id of a particular record), you would change the final for loop to be a bit more restrictive.
For example, instead of starting at 1, start from 5 pages before the current page. And instead of ending at $total, end at 5 pages after the current page.
$start = $id - 5.
if ($start < 1) {
$start = 1;
}
$end = $id + 5;
if ($end > $total) {
$end = $total;
}
for ($i = $start; $i <= $end; $i++) {
// echo pagination options
}
You could also modify this to give links that will get you closer to where you want to go (i.e. if displaying pages 20 to 30, of 100 pages, show links for pages 10, 40, 50 and 60, or even supply an input box to let you jump to a specific page.

Pagination in search php

I have a search form and i want to put a pagination, but when i press the next button or second page on the search using pagination , all the results get messed up, and there is no data being fetched from the query. I don't know where the exact problem could be, but this is my search code:
include ('paginate.php'); //include of paginat page
$per_page = 5;
$find = $_POST['find'];
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find); // number of results to show per page
$result = mysql_query("SELECT * FROM projects WHERE p_name LIKE '%$find%'");
$total_results = mysql_num_rows($result);
$total_pages = ceil($total_results / $per_page);//total pages we going to have
//------------if page is setcheck-----------------//
if (isset($_GET['page'])) {
$show_page = $_GET['page']; //it will telles the current page
if ($show_page > 0 && $show_page <= $total_pages) {
$start = ($show_page - 1) * $per_page;
$end = $start + $per_page;
} else {
// error - show first set of results
$start = 1;
$end = $per_page;
}
} else {
// if page isn't set, show first set of results
$start = 0;
$end = $per_page;
$show_page=1;
}
// display pagination
if(isset($_GET['page'])){
$page = intval($_GET['page']);
}else{
$page =1;
}
$tpages=$total_pages;
if ($page <= 0)
$page = 1;
?>
<?php
$reload = $_SERVER['PHP_SELF'] . "?tpages=" . $tpages;
echo '<div class="pagination"><ul>';
if ($total_pages > 1) {
echo paginate($reload, $show_page, $total_pages);
}
echo "</ul></div>";
// display data in table
echo "<table class='table table-bordered'>";
echo "<thead><tr><th>Project</th> <th>Country</th> <th>Active</th>
</tr></thead>";
for ($i = $start; $i < $end; $i++) {
// make sure that PHP doesn't try to show results that don't exist
if ($i == $total_results) {
break;
}
?><form name="frmactive" method="POST" action="">
<input type="hidden" name="id" value="<?php echo mysql_result($result, $i, 'p_id');?>" />
<?php
// echo out the contents of each row into a table
echo '<tr><td>' . mysql_result($result, $i, 'p_name') . '</td>';
echo '<td>' . mysql_result($result, $i, 'p_country') . '</td>';
if (mysql_result($result, $i, 'p_isActive')=='1'){
echo '<td>Active</td>';
echo '<td align="center">Edit</td>';
}
else{
echo'<td>Inactive</td> ';
echo '<td align="center">Edit</td>';
echo "</tr>";
}
// close table>
}
echo "</table>";
// pagination
?>
and this is the paginate.php
function paginate($reload, $page, $tpages) {
$adjacents = 2;
$prevlabel = "‹ Prev";
$nextlabel = "Next ›";
$out = "";
// previous
if ($page == 1) {
$out.= "<span>" . $prevlabel . "</span>\n";
} elseif ($page == 2) {
$out.= "<li>" . $prevlabel . "\n</li>";
} else {
$out.= "<li>" . $prevlabel . "\n</li>";
}
$pmin = ($page > $adjacents) ? ($page - $adjacents) : 1;
$pmax = ($page < ($tpages - $adjacents)) ? ($page + $adjacents) : $tpages;
for ($i = $pmin; $i <= $pmax; $i++) {
if ($i == $page) {
$out.= "<li class=\"active\"><a href=''>" . $i . "</a></li>\n";
} elseif ($i == 1) {
$out.= "<li>" . $i . "\n</li>";
} else {
$out.= "<li>" . $i . "\n</li>";
}
}
if ($page < ($tpages - $adjacents)) {
$out.= "<a style='font-size:11px' href=\"" . $reload . "&page=" . $tpages . "\">" . $tpages . "</a>\n";
}
// next
if ($page < $tpages) {
$out.= "<li>" . $nextlabel . "\n</li>";
} else {
$out.= "<span style='font-size:11px'>" . $nextlabel . "</span>\n";
}
$out.= "";
return $out;
}
Could you please point out where the bug is taking place ? Thank you for your time
Try this (pay attention to the comments please) :
<?php
/*
Assuming that your search form has a POST method set to it,
be sure to do a redirect to this page and send the find parameter gotten
from the posted form urlencoded
ie path_to_my_file?find='.urlencode(trim($_POST['find']))
*/
include ('paginate.php'); //include of paginat page
$per_page = 5;
$find = strip_tags(strtoupper(trim(urldecode($_GET['find']))));
$page = intval($_GET['page']);
$result_total = mysql_query("SELECT COUNT(*) AS total FROM projects WHERE p_name LIKE '%".$find."%'");
$tmp_total = mysql_fetch_assoc($results_total);
$totalpages = ceil($tmp_total['total'] / $per_page);
if ($totalpages != 0 && $page > $totalpages) {
$page = $totalpages;
} else if ($page < 1) {
$page = 1;
}
$offset = ($page - 1) * $per_page;
$result = mysql_query("SELECT * FROM projects WHERE p_name LIKE '%".$find."%' LIMIT ".$offset.", ".$per_page);
$show_page = 1;
//You need to pass the phrase you are searching for in every link in order for the pagination to work (or user Sessions to save the keyword somewhere if you don't want it in the link)
$reload = $reload = 'http://localhost/Personal/Stackoverflow/2/index.php?find='.urlencode($find);
echo ' <div class="pagination">
<ul>';
if ($totalpages > 1) {
echo paginate($reload, $show_page, $totalpages);
}
echo ' </ul>
</div>';
// display data in table
if(mysql_num_rows($result) > 0) {
echo ' <table class="table table-bordered">
<thead>
<tr>
<th>Project</th>
<th>Country</th>
<th>Active</th>
</tr>
</thead>';
while($row = mysql_fetch_assoc($result)) {
echo ' <tr>
<td>'.$row['p_name'].'</td>
<td>'.$row['p_country'].'</td>
<td>'.((intval($row['p_isActive']) == 1) ? 'Active' : 'Inactive').'</td>
<td align="center">
Edit
</td>
</tr>';
}
echo ' </table>';
}
?>

Duplicating a class

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.

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.

How to make the pagination class in Codeigniter work with AJAX?

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);
});
};

Categories