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 !
Related
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>';
}
?>
Description: Trying to do a title search for videos within a PHP page with AJAX pagination.
Problem: "Search" button does not do anything when pressed. Instead, if I write something in "keywords" field and switch from page 1 to page 2 the date gets updated and shows videos with matching title. If I delete what I wrote in "keywords" field, and switch again between pages, the data gets updated. As mentioned, "Search" button does not work.
Fix: I would like to write in the text field and press "Search" button. The page should then update and show only the videos with the matching title.
search.php:
<!-- Testing the search -->
<p><b> Search all videos in database below: </b></p>
<ul>
<li>
<label for="keywords">Keywords</label>
<input type="text" id="keywords" name="keywords" size="50" maxlength="64" />
</li>
<li>
<input type="button" value="Search" onclick="loadData()" />
</li>
</ul>
search_videos.js:
* 'page' variable is used for pagination
...
function loadData(page){
$.ajax
({
type: "POST",
url: "search_videos.php",
data: { 'page': page, 'keywords': $('#keywords').val() },
success: function(msg)
{
loading_hide();
$("#container").html(msg);
}
});
}
...
Update: Below is what I get, after I press 2nd page and then 1st page again.
POST results:
Raw results (sorry for bad formatting):
005<div class='data' style='margin-bottom:10px'><ul><img src="images/link_pic.png" alt="error" width="164" height="128"><li>Title: <b>Video 1</b></br> Uploaded by: user1</br>Date added: 13/07/2013</li></br></br><img src="images/link_pic.png" alt="error" width="164" height="128"><li>Title: <b>ghg</b></br> Uploaded by: cacamaca</br>Date added: 21 Jul 2013 16:03</li></br></br><img src="images/link_pic.png" alt="error" width="164" height="128"><li>Title: <b>s</b></br> Uploaded by: cacamaca</br>Date added: 21 Jul 2013 16:23</li></br></br><img src="images/link_pic.png" alt="error" width="164" height="128"><li>Title: <b>s</b></br> Uploaded by: cacamaca</br>Date added: 21 Jul 2013 16:24</li></br></br><img src="images/link_pic.png" alt="error" width="164" height="128"><li>Title: <b>dg</b></br> Uploaded by: gdfgdf</br>Date added: data azi</li></br></br></ul></div><div class='pagination'><ul><li class='inactive'>Previous</li><li p='1' style='color:#fff;background-color:#006699;' class='active'>1</li><li p='2' class='active'>2</li><li p='2' class='active'>Next</li>
This is what I get when I press search button now:
This is a bit long, the first part of the code should be relevant to the problem. Here is the code for:
search_videos.php :
<?php
if($_POST['page'])
{
$page = $_POST['page'];
$cur_page = $page;
$page -= 1;
$per_page = 5;
$previous_btn = true;
$next_btn = true;
$start = $page * $per_page;
include"core/database/connect.php";
// Get the input of the selected video
$input = $_POST['input'];
//$input = 'video';
echo $input;
echo $page;
echo $start;
echo $per_page;
// protect against sql injection and ignore multiple spaces in the input
$keywords = preg_split('#\s+#', mysql_real_escape_string($input));
// query the database by user input title
$by_title = "LOWER(`V_TITLE`) LIKE '%" . implode("%' OR `V_TITLE` Like '%", $keywords) . "%'";
$query_pag_data = "SELECT * from upload WHERE $by_title LIMIT $start, $per_page";
$result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error());
$msg = "";
while ($row = mysql_fetch_array($result_pag_data)) {
$msg .= '<img src="images/link_pic.png" alt="error" width="164" height="128">' . '<li>Title: <b>' . $row['V_TITLE'] . '</b></br> Uploaded by: ' . $row['V_USERNAME'] . '</br>Date added: ' . $row['V_DATE'] . '</li></br></br>';
}
$msg = "<div class='data' style='margin-bottom:10px'><ul>" . $msg . "</ul></div>"; // Content for Data
/* --------------------------------------------- */
$query_pag_num = "SELECT COUNT(*) AS count FROM upload";
$result_pag_num = mysql_query($query_pag_num);
$row = mysql_fetch_array($result_pag_num);
$count = $row['count'];
$no_of_paginations = ceil($count / $per_page);
/* ---------------Calculating the starting and endign values for the loop----------------------------------- */
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>";
// FOR ENABLING THE PREVIOUS BUTTON
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>";
}
// TO ENABLE THE NEXT BUTTON
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>";
}
echo $msg;
// de-allocate memory that was used to store the query results returned by mysql_query(), improve performance
mysql_free_result($query_pag_data);
}
The problem was with the javascript. The pagination is given by the ajax response and it seems that in some cases (or all; I didn't study the issue that deep) javascript events can't be fired after the elements to which they were bound are dynamically added to the page. The very easy to use live() method is deprecated since jQuery 1.7. What worked now was:
$('#container').on('click','.pagination li.active', function(){//... the ajax request here}
The difference between live() and on() is that the element to which you would normally bind the event is the second argument of the on() method and the on() method is called on the parent of the element.
I am working on a php ajax pagination.
The problem is that it wont ad the class="highlightActivePage" proper.
If I click on 1 - 2 - 3 , it works fine and highlight the number 3 if im on page 3.
But soon as I click on page 4 it highlights page 5 instead, etc.
Not sure if my for loop is wrong, but here us my code:
if (paginationHTML == "")
{
paginationHTML += "<ul>";
if (adResultsData.show_first_text == 1)
{
paginationHTML += "<li><a href='#' onclick='fetchResults(1);'>First</a></li>";
}
if (adResultsData.show_previous_text == 1)
{
paginationHTML += "<li><a href='#' onclick='fetchResults(" + (adResultsData.current_page - 1) + ");'>Prev</a></li>";
}
for (var i = 0; i < adResultsData.pages.length; i++)
{
if (adResultsData.current_page == (i + 1))
{
paginationHTML += "<li><a href='#' class='highlightActivePage' onclick='fetchResults(" + adResultsData.pages[i] + ");'>" + adResultsData.pages[i] + "</a></li>";
}
else
{
paginationHTML += "<li><a href='#' onclick='fetchResults(" + adResultsData.pages[i] + ");'>" + adResultsData.pages[i] + "</a></li>";
}
}
if (adResultsData.show_next_text == 1)
{
paginationHTML += "<li><a href='#' onclick='fetchResults(" + (adResultsData.current_page + 1) + ");'>Next</a></li>";
}
if (adResultsData.show_last_text == 1)
{
paginationHTML += "<li><a href='#' onclick='fetchResults(" + adResultsData.number_of_pages + ");'>last</a></li>";
}
paginationHTML += "</ul>";
paginationHTML += pageSpan.innerHTML = "<br>Page " + adResultsData.current_page + " of " + adResultsData.number_of_pages;
}
php
$numberOfPages = $results['pages'];
$currentPage = $results['currentPage'];
if ($currentPage != 1 && $currentPage != 2)
{$showFirst = 1;}
else $showFirst = 0;
if ($currentPage != 1)
{$showPrevious = 1;}
else $showPrevious = 0;
if ($currentPage != $numberOfPages)
{$showNext = 1;}
else $showNext = 0;
if ($currentPage != $numberOfPages && $currentPage != ($numberOfPages - 1))
{$showLast = 1;}
else $showLast = 0;
if ($currentPage <= 5 && $numberOfPages <= 5 || $numberOfPages <= 5)
{$startingPage = 1;}
else if ($currentPage == 1 || $currentPage == 2)
{$startingPage = 1;}
else
{$startingPage = $currentPage - 2;}
$pageNumbers = [];
for ($i = $startingPage; $i < ($startingPage + 5) && $i <= $numberOfPages; $i++)
{
$pageNumbers[] = $i;
}
$pagesString = implode(", ", $pageNumbers);
$listingsString = implode(", ", $listingsArray);
$jsonString = <<< END
{
"resultsTotal" : $numberOfResults,
"listings" : [$listingsString],
"number_of_pages" : $numberOfPages,
"current_page" : $currentPage,
Thanks!
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.
This is a pagination code used for the navigation, any ideas how to get this code to display simply a numbered list of the pages as links?
if (isset($_GET['pageno'])) {
$pageno = $_GET['pageno'];
}
else {
$pageno = 1;
}
if(isset($_GET['niche']))
{
$query = "SELECT count(*) FROM studies WHERE niche = '{$_GET['niche']}'";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
}
$query_data = mysql_fetch_row($result);
$numrows = $query_data[0];
$rows_per_page = 4;
$lastpage = ceil($numrows/$rows_per_page);
$pageno = (int)$pageno;
if ($pageno > $lastpage) {
$pageno = $lastpage;
}
if ($pageno < 1) {
$pageno = 1;
} // if
$limit = 'LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page;
$query = "SELECT * FROM studies WHERE niche = '{$_GET['niche']}' $limit";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
and...
if ($pageno == 1) {
echo "<div class='container'>FIRST PREV ";
} else {
echo "<div class='container'> <a href='{$_SERVER['PHP_SELF']}?pageno=1&niche={$_GET['niche']}'>FIRST</a> ";
$prevpage = $pageno-1;
echo " <a href='{$_SERVER['PHP_SELF']}?pageno=$prevpage&niche={$_GET['niche']}'>PREV</a> ";
} // if
echo " ( Page $pageno of $lastpage ) ";
if ($pageno == $lastpage) {
echo " NEXT LAST</div><br />";
} else {
$nextpage = $pageno+1;
echo " <a href='{$_SERVER['PHP_SELF']}?pageno=$nextpage&niche={$_GET['niche']}'>NEXT</a> ";
echo " <a href='{$_SERVER['PHP_SELF']}?pageno=$lastpage&niche={$_GET['niche']}'>LAST</a></div><br /> ";
} // if
?>
Try this:
$totalpages = ceil($numrows / $rows_per_page);
if($totalpages >= 1){ $pagelinkcount = 1; } else { $pagelinkcount = 0; }
while($pagelinkcount <= $totalpages && $totalpages > 1) {
echo "{$pagelinkcount} ";
$pagelinkcount++;
}
On a side note, as Ian Elliot pointed out in the comments for your question, using $_GET in an SQL query leaves your database VERY vulnerable, and is thus considered an extremely insecure coding practice. You should escape and parse the $_GET data that you need diligently before passing it to the DB.
Here's a function I've been using for pagination for a while. It returns nothing if there's only one page, returns up to 15 pages with numbers, then adds a dropdown that lets you skip to any 10th page when there are more than 15 pages. It relies on some prev/next images, but you can easily take that out.
function paginate( $items_per_page, $number_of_results ) {
if( isset( $_REQUEST['page'] ) ) {
$page = $_REQUEST['page'];
} else {
$page = 1;
}
$url = htmlentities( preg_replace( '/(\?|&)page=[\d]+/', '', $_SERVER['REQUEST_URI'] ).'&' );
$html = '';
$numbers_html = '';
$navigation_html = '';
if( $number_of_results > $items_per_page ) {
$html .= '<div class="pagination">';
if( $page == 1 or $page == '1' ) {
$numbers_html .= '<img src="images/prev.png" alt="← prev" class="inactive" /> - ';
} else {
$numbers_html .= '<img src="images/prev.png" alt="← prev" /> - ';
}
$count = 0;
$total_pages = ceil( $number_of_results / $items_per_page )-1;
while( $count <= $total_pages ) {
$count++;
if( $total_pages > 12 and floor($count / 10) != floor($page / 10) ) {
while( $count < $total_pages and floor($count / 10) != floor($page / 10) ) {
if( $count == 1 ) {
$endpage = 9;
} elseif( $count + 9 < $total_pages ) {
$endpage = $count + 9;
} else {
$endpage = $total_pages + 1;
}
$ten_group = floor( $count / 10 );
if( $ten_group == 0 ) {
$navigation_html .= '<option value="'.$url.'page='.$count.'">page 1</option>';
} else {
$navigation_html .= '<option value="'.$url.'page='.$count.'">page '.($ten_group*10).'</option>';
}
$count += 10;
}
$count -= 2;
} else {
if( $page == $count ) {
$numbers_html .= '<span class="current">'.$count.'</span>';
if( $count == 1 ) {
$endpage = 9;
} elseif( $count + 9 < $total_pages ) {
$endpage = $count + 9;
} else {
$endpage = $total_pages + 1;
}
if( $total_pages > 15 ) {
$ten_group = floor( $count / 10 );
if( $ten_group == 0 ) {
$navigation_html .= '<option value="'.$url.'page='.$count.'" selected="selected">page 1</option>';
} else {
$navigation_html .= '<option value="'.$url.'page='.$count.'" selected="selected">page '.($ten_group*10).'</option>';
}
}
} else {
$numbers_html .= ''.$count.'';
}
if( ( $total_pages > 12 and $count % 10 == 9 ) or $count == $total_pages+1 ) {
} else {
$numbers_html .= ' - ';
}
}
}
if( $page != $count ) {
$numbers_html .= ' - <img src="images/next.png" alt="next →" />';
} else {
$numbers_html .= ' - <img src="images/next.png" alt="next →" class="inactive"/>';
}
$count++;
$html .= '<div class="pagination_numbers">'.$numbers_html.'</div>';
if( $navigation_html ) {
$html .= '<div class="pagination_navigation">skip to: <select onchange="window.location=this.value">'.$navigation_html.'</select> of '.($total_pages+1).'</div>';
}
$html .= '</div>';
}
return $html;
}
If you have many pages to display, you might want to consider "logarithmic" page naviagtion, as I describe in my answer here:
How to do page navigation for many, many pages? Logarithmic page navigation
(Sample PHP code only handles the pagination display - not the DB query).