This question already has answers here:
Simple PHP Pagination script [closed]
(3 answers)
Closed 4 years ago.
I'm selecting data from database and I want to limit result by X amount and then show the number of rows left and showing button below to navigate to next page of the result (continues until there's no more result in database).
How do i do this.
my code is only fetching it...but how do I add the page 1,2,3,4,5
something like stackOverflow tags page
my code:
<?PHP
$SQL = "SELECT * FROM $tags_table LIMIT 20";
$Q = queryDB($SQL);
if (mysqli_num_rows($Q)) {
while ($row = mysqli_fetch_assoc($Q)) {
$tag_id= $row['tag_id'];
$details = $row['details'];
$tagName= $row['tag_name'];
$HTML_temp = "<div class='grid-view page-cell'>
<div class='page-header'><a href='#' class='post-page'>{$tagName}</a></div>
<div class='details'>{$details}</div>
</div>";
ECHO $HTML_temp;
}
}
?>
I created an answer to this feature. Below are my code for future use.
PHP:
<?PHP
//count the number of rows in db
function countTags(){
global $conn, $tags_table;
$SQL = "SELECT COUNT(tag_id) FROM $tags_table";
return mysqli_fetch_array(queryDB($SQL))[0];
}
//Pager:
//Show next pages box if $options["NumOfRecords"] is greater than 20
//We fetching 20 records per page -- Adjust to your needs
function pager(array $options = array()){
$options = array_merge(array(
'NumOfRecords' => 0, //number of records from database
'maxPager' => 5, //number pager to show eg. 1-5
'maxPageRecords' => 20 // since I need 20 records maximum per/page
),$options);
$rows = (int) $options['NumOfRecords'];
$maxPager = (int) $options['maxPager'];
$maxPageRecords = (int) $options['maxPageRecords'];
//offset records
$offset = $rows - $maxPageRecords; //since our max records per page is 20
$totalPages = ceil($rows/$maxPageRecords); //move it to neart heigher number
$numOfPagesLeft = $totalPages-1; //pages left
if ($numOfPagesLeft) {
//check if tab_id is set
$tab_id = $activePage = isset($_GET['tab_id']) && (int)$_GET['tab_id'] ? (int)$_GET['tab_id']:1;
//store pager here
$pagerArray = array();
//url to page we working on
$URL = DOMAIN().'/'.(IsadminLogin() ? ("apps/tags/") :"tags/");
$i = 0; //pager counter
for ($row=0; $row < $numOfPagesLeft; $row++ ) {
$i++;
//show only five pager
if ($offset && $i <= $maxPager && $activePage !== $totalPages && $totalPages != $tab_id) {
$page_id = $tab_id++;
$href = $URL .$page_id;
$active = ($activePage == $page_id ? "current":"random");
$ellipse = ($i== $maxPager && $tab_id !== ($offset/$maxPageRecords) ? "<span class='page-numbers dots'>...</span>":"");
$pagerArray[] = "<a class='page-numbers {$active}' href='{$href}/'>{$page_id}</a>{$ellipse}";
}
}
//add previous page
if ($activePage > 1) {
//previous pagers
$prev = $activePage -1;
$prevHref = $URL .$prev;
$prevPagers = $activePage > 2 ? "<a class='page-numbers prv' href='{$URL}1'>1</a><span class='page-numbers dots'>...</span>":"";
array_unshift($pagerArray , "<a class='page-numbers prev' href='{$prevHref}/'>prev</a>{$prevPagers}");
}
//show next button if offset is true
if ($numOfPagesLeft) {
//next pagers
$next = $activePage +1;
$nextHref = $URL.$next;
$lastPager = $totalPages;
$PagerLast = $URL.$lastPager;
$active = ($activePage == $lastPager ? "current":"random");
$pagerS = $lastPager ? "<a href='{$PagerLast}' class='page-numbers {$active}'>{$lastPager}</a>":"";
array_push($pagerArray , $totalPages != $tab_id ? "{$pagerS} <a class='page-numbers prev' href='{$nextHref}/'>next</a>":"{$pagerS}");
}
//implode pager
return join('',$pagerArray);
}
}
$maxPageRecords = 20; //since we fetching 20 records/page
$tab_id = isset($_GET['tab_id']) && (int)$_GET['tab_id'] > 0 ? (int)$_GET['tab_id']:1;
$offset = $tab_id == 1 ? 0:($tab_id > 1 ? ($tab_id-1) *$maxPageRecords:0);//calculate offset for SQL
$SQL = "SELECT * FROM $tags_table LIMIT {$maxPageRecords} OFFSET {$offset}";
$Q = queryDB($SQL);
$NR = mysqli_num_rows($Q);// number of rows returned
if ($NR) {
while ($row = mysqli_fetch_assoc($Q)) {
$tag_id = $row['tag_id'];
$details = $row['details'];
$TagName = $row['tag_name'];
$HTML_temp = "<div class='grid-view tag-cell'>
<div class='excerpt-header'><a href='#' class='post-tag'>{$TagName}</a></div>
<div class='excerpt'>{$details}</div>
</div>";
ECHO $HTML_temp;
}
}else{
ECHO "No tags found in database";
}
//echo $offset;
//GET current domain name
$LOCALIP = array('127.0.0.1','::1');
$sitename = "school";
$HostStatus = !in_array(GET_IP(), $LOCALIP)? TRUE:FALSE; //hosting local or remote server
function DOMAIN(){global $HostStatus,$sitename;if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&$_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') { $domain = 'https://'.str_replace(array('https://www.','http://www.','www.'), '', ($_SERVER['SERVER_NAME'])).($HostStatus ? '':'/'.$sitename);}else {$domain = 'http://'.str_replace(array('https://www.','http://www.','www.'), '', ($_SERVER['SERVER_NAME'])).($HostStatus ? '':'/'.$sitename);} return $domain;}function GET_IP(){if (!empty($_SERVER['HTTP_CLIENT_IP'])) {$ip=$_SERVER['HTTP_CLIENT_IP'];}elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];}else{$ip=$_SERVER['REMOTE_ADDR'];}return $ip;}
?>
HTML:
Lets call pager() function
<div class='pager'>
<div class='col-lg-12 no-padding'>
<div class='col-lg-2'></div>
<div class='col-lg-4'></div>
<div class='col-lg-6 no-padding'>
<div class="pager rfloat">
<?PHP
//call pager() on the button of the page u want to show pagwer boxes
ECHO pager(array(
'maxPageRecords'=>20,
'NumOfRecords'=>countTags(), //records could be any number e.g. 400,200,52,12..make sure its coming from DB
'maxPager'=>5));
?>
</div>
</div>
</div>
</div>
CSS:
.pager a{
display: inline-block;
padding: 4px 8px;
font-size: 12px;
color: #848d95;
border: 1px solid #e4e6e8;
border-radius: 3px;
background-color: transparent;
margin-left: 5px;
}
.page-numbers.current,.page-numbers:hover{
transition: all ease-in-out .2s;
color: #FFF;
background-color: #ff7308;
border-color: transparent;
}
.page-numbers.dots{
color: #848d95;
background-color: transparent;
border-color: transparent;
box-shadow: none;
padding:0 15px;
letter-spacing: 3px;
}
Related
I have the following code to enter the positions, etc.
I have two problems:
The position numbers show like 1, 2, 2, 2, 2 instead of 1, 2, 3, 4, 5
It would be "Days" even if the number of days is 1. I am uploading a screenshot.
Thank you very much for your input.
https://postimg.cc/mhQHqqyk
if (isset($_GET['boardcount']) && is_numeric($_GET['boardcount']) && $_GET['boardcount'] > 0) {
$boardcount = $_GET['boardcount'];
} else {
$boardcount = 20;
}
$getleaderboard = lfmsql_query("SELECT a.days AS days, b.firstname AS firstname, b.lastname AS lastname, b.email AS email FROM `".$prefix."surftarget_logs` a LEFT JOIN `".$prefix."members` b ON (a.userid=b.Id) WHERE a.date='".$todaydate."' OR a.date='".$yesterdate."' ORDER BY a.days DESC") or die(lfmsql_error());
$position = 1;
$lastdays = 0;
$boardoutput = '';
while ($position <= $boardcount && $leaderlist = lfmsql_fetch_assoc($getleaderboard)) {
$gravatarimg = "https://www.gravatar.com/avatar/".md5($leaderlist['email'])."?d=mm";
if (isset($_GET['usetable']) && $_GET['usetable'] > 0) {
$boardoutput .= '<tr><td style="background-color:#15aa00; padding: 15px; width:360px; color:#fff; border:solid; border-width: 1px 0; border-color:#fff;">
<h5>#'.$position.' <img style="max-height:50px; max-width:50px;" src="'.$gravatarimg.'"> '.$leaderlist['firstname'].' '.$leaderlist['lastname'].'</h5>
<span>'.$leaderlist['days'].' days</span>
</td></tr>';
} else {
$boardoutput .= '<li class="media list-group-item" style="background-color:#15aa00; color:#fff;">
<div class="media-body">
<h5 class="mt-0 mb-1">#'.$position.' <img style="max-height:50px; max-width:50px;" src="'.$gravatarimg.'"> '.$leaderlist['firstname'].' '.$leaderlist['lastname'].'</h5>
<p>'.$leaderlist['days'].' days</p>
</div>
</li>';
}
if ($leaderlist['days'] > $lastdays) {
$position = $position + 1;
$lastdays = $leaderlist['days'];
}
}
This seems to be a logical bug in your code. As per the screenshot, it appears that it is not going inside the if block the second time onwards. you have to keep >= under if condition if you really want to increment them.
Modify this code:-
if ($leaderlist['days'] > $lastdays) {
$position = $position + 1;
$lastdays = $leaderlist['days'];
}
To:-
if ($leaderlist['days'] >= $lastdays) {
$position = $position + 1;
$lastdays = $leaderlist['days'];
}
Note:- >= symbol.
I have developed a page that shows the details of user achievements. I have a table that holds the level of the user.
Users( id, username, password, sum_score, level)
Based on the value present in level(i.e., from 0 to 5) I would like to like to display stars in the user page.
I tried something like :
$stars = "";
$s = 1;
while ($s<=$lvl['level']) {
$stars.="★";
$s++;
}
echo "$stars";
The above code produces star based on the level.(i.e., if the level is 1 it shows one star on the page). But I want to display 5 stars and fill the stars based on the level in the table. Can Someone help me out.
Instead of using while, you can use a simple for loop in this case.
Assuming $lvl['level'] is properly getting database's data (i.e., 5), you can loop until 5 compare it with $lvl['level'] value, and display the star based on the if statement's result. Like so:
$stars = "";
for ($i = 1; $i <= 5; $i++) {
$i <= $lvl['level'] ? $stars .= "★" : $stars .= "☆";
}
echo $stars;
str_repeat is one option.
// stub for your record
$lvl = [
'level' => 4
];
// render
$maxStars = 5;
$stars = (int)$lvl['level'];
$output =
str_repeat('★', $stars) .
str_repeat('☆', $maxStars - $stars) .
' stars';
echo $output;
Output: https://3v4l.org/UFprQ
If you add some classes and holders and add one if statement in the loop
<?php
$lvl = ["id" => 1, "level" => 4];
$stars = "";
for ($i = 1; $i < 6; $i++) {
$stars .= '<span' . (($i <= $lvl["level"]) ? ' class="fill"' : '') . '>';
$stars .='★</span>';
}
echo '<div class="star"><div class="rating">' . $stars . '</div></div>';
Here is the snippet, HTML code is the output of the PHP:
.star {
width: 200px;
position: relative;
color: #bdbdbd;
}
.rating span {
font-size: 30px;
margin-left: -4px;
white-space: nowrap;
overflow: hidden;
}
.rating span:before {
content: "\2605";
position: absolute;
color: gray;
}
.rating span.fill:before {
content: "\2605";
position: absolute;
color: gold;
}
<!-- this will be the output generated from php code used above !-->
<div class="star">
<div class="rating"><span class="fill">★</span><span class="fill">★</span><span class="fill">★</span><span>★</span><span>★</span></div>
</div>
I'm using bootstrap in the whole document, I'm using it for the pagination too.
This link is awesome: PHP & MySQL Pagination
and it helped me a lot coding the method for pagination (I am using postgre, I changed a few things).
When I print each button for the pagination, I am using bootstrap's code:
http://www.w3schools.com/bootstrap/bootstrap_pagination.asp
<ul class=\"pagination pagination-sm\">$links</ul>
and:
$links .= ($i != $page ) ? "<li><a href='$explode[0]$final$i'>$i</a><li> " : "";
for concatenating new strings to the $links variable(of course first this then echoing $links).
Note: I am using explode() because I get my URL and I fix the the &page=
My question is:
How do I shorten the number of buttons to show per page?
At the moment my situation is the one in the screenshot.
I'd love to get something like:
[current][2][3][4][5]...[61][62]
EDIT:
I changed the code to have the "current":
if ($i != $page) {
$links.="<li><a href='$explode[0]$final$i'>$i</a><li>";
} else {
$links.="<li class=\"active\"><a href='#'>current</a><li>";
}
}
EDIT:
added new image thanks to 1st solution (it is now black because I changed theme in the meantime).
EDIT: adding the php code.
$perPage = addslashes(strip_tags(#$_GET["perPage"]));
$page = addslashes(strip_tags(#$_GET['page'])) ?: '1';
$startAt = $perPage * ($page - 1);
SWITCH ($direction){
case "SENT":
$count = "SELECT count(*) as total, 'SENT' as direction FROM sent WHERE date >= '$fdate' AND date <= '$tdate' AND identification LIKE '%$identification%' ";
$query = "SELECT *,'SENT' as direction FROM sent WHERE date >= '$fdate' AND date <= '$tdate' AND identification LIKE '%$identification%' ";
break;
}
$res = pg_fetch_assoc(pg_query($conn, $count));
$total = ceil($res['total'] / $perPage);
if (empty($total1)) { $total1 = '0'; } else { $total1 = ceil($res['total1'] / $perPage); }
$totalPages = $total + $total1;
$links = "";
$absolute_url = full_url( $_SERVER );
for ($i = 1; $i <= $totalPages; $i++) {
$explode = explode("&page=", $absolute_url);
$final="&page=";
if ($i != $page) {
$links.="<li><a href='$explode[0]$final$i'>$i</a><li>";
} else {
$links.="<li class=\"active\"><a href='#'>current</a><li>";
}
}
$query .= "order by date DESC OFFSET '$startAt' LIMIT '$perPage' ";
$result = pg_query($conn, $query);
EDIT:
Found the problem in the jquery:
it will not load, never, but when I call the function at the document=ready status, it will.
<script>
$(document).ready(function(){
$('#paginateblock').css('margin-left','-110px');
});
</script>
I need this to work always, not only when the document is "ready", rather, at every click on 'paginateblock' or everytime I change page.
Anybody can help?
SOLUTION #1:
Thanks to the help of S Gandhe that provided me his code, I'm copying it here with my correction.
for ($i = 1; $i <= $totalPages; $i++) {
if($page >= 7){
$start = $page -4;
} else {
$start = $i;
}
$end = ($start + 7 < $totalPages)?($start + 7):$totalPages;
for ($start; $start <= $end ; $start++) {
$explode = explode("&page=", $absolute_url);
$final="&page=";
$css_class = ($page == $start ) ? "class='active'" : "";
$links .= "<li><a href='$explode[0]$final$start'>$start</a><li>";
}
}
CSS: [the css for <li> did not change]
#page-selection{
width:350px;
height:36px;
overflow:hidden;
}
HTML/PHP
<div id="page-selection"><?php echo "<ul class=\"pagination pagination-sm\">$links</ul>"; ?></div>
SOLUTION #2 - FINAL:
I modified the code a bit more, the pagination buttons are inside a <div> and the content is aligned.
Plus, Page #1 and #lastpage are always shown.
CODE:
for ($i = 1; $i <= $totalPages; $i++) {
if($page >= 4){
$start = $page -3;
} else {
$start = $i;
}
$end = ($start + 6 < $totalPages)?($start + 6):$totalPages;
for ($start; $start <= $end ; $start++) {
$explode = explode("&page=", $absolute_url);
$final="&page=";
$css_class = ($page == $start ) ? "class='active'" : "";
$links .= "<li><a href='$explode[0]$final$start'>$start</a></li>";
}
$firstpage = "<li><a href='$explode[0]$final'1><<</a></li>";
$lastpage = "<li><a href='$explode[0]$final$totalPages'>>></a></li>";
}
HTML:
<div id="page-selector">
<div class="page-selector-field"><?php echo "<ul class=\"pagination pagination-sm\">$firstpage</ul>"; ?></div>
<div id="page-selection" class="page-selector-field"><?php echo "<ul class=\"pagination pagination-sm\">$links</ul>"; ?></div>
<div class="page-selector-field"><?php echo "<ul class=\"pagination pagination-sm\">$lastpage</ul>"; ?></div>
</div>
CSS:
#page-selection{
width:344px;
height:36px;
overflow:hidden;
}
#page-selector{
width: 450px;
height:36px;
overflow:hidden;
/*margin: 0 auto; uncomment this if you want this bar centered */
}
.page-selector-field{
width:50px;
height:36px;
overflow:hidden;
float: left;
}
ul.pagination {
display: inline-block;
padding: 0;
margin: 0;
}
ul.pagination li {
display: inline;
width: 50px;
}
ul.pagination li a {
display: block;
width: 50px;
text-align:center;
float: left;
padding: 8px 16px;
text-decoration: none;
}
am not sure about the quality/performance of code, but you can do it multiple ways, 2 of them here.
I actually started using lazy load and auto loading of pages when scroll rather page numbers, so I don't have the code.
1) JS/CSS:You can create a fix width div for page numbers and scroll to current page using current page number * each div width.
let's say your current page is 54 and each page number is taking 50px. you will set the margin left to -2000px something.
$('#paginateblock').css('margin-left','-110px');
https://jsfiddle.net/66wy0t19/3/
2) PHP : as you said you have the links in array. you can use array_splice to get just the 10 links based on current page number. so if it's 54. you will may be spice it from 50-60 for showing 10.
now you will need 2 buttons. one to move the page numbers div and second to get to Next page (like 4th from 3rd).
Update:
Couldn't find the js code, but here is some code based on php solution.
one minor advantage is you won't print all 100 items on page rather just print 5 links.
echo "<ul class='pagination wrap'>";
if ($this->pageNumber - 1) {
echo "<li ><a href='{$this->url}/page_" . ($this->pageNumber - 1) . "/' {$ajax_request}><<</a></li>";
}
$start =($this->pageNumber > 5)?$this->pageNumber -4:1;
$end = ($i + 5 < $this->total_pages)?($start+5):$this->total_pages;
for ($start; $start <= $end ; $start++) {
echo "<li {$css_class}><a href='{$this->url}/page_{$i}/' {$ajax_request} >{$i}</a></li>";
}
if ($this->total_pages - $this->pageNumber > 1) {
echo "<li ><a href='{$this->url}/page_" . ($this->pageNumber + 1) . "/' {$ajax_request}>>></a></li>";
}
echo "</ul>";[![the output looks like this. ofcourse with classes. but i use bootstrap too.][1]][1]
Update 2:
Assuming each page number is taking 50px. this should work.
var currentPage =27;
var paginateBlockMargin = (Math.ceil(currentPage/2) * 100)-100;
$('#paginateblock').css('margin-left', '-'+paginateBlockMargin+'px');
Check t https://jsfiddle.net/66wy0t19/14/
This is the PHP code using your variables. You would need to replace your for loop with following. Prefer PHP code, as you will still need a lot of consideration in above JS. I wish I could find that JS code I had. sad.
if($page > 5){
$start = $page -4;
}
$end = ($start + 5 < $totalPages)?($start + 5):$totalPages;
for ($start; $start <= $end ; $start++) {
$explode = explode("&page=", $absolute_url);
$final="&page=";
$css_class = ($page == $start ) ? "class='active'" : "";
$links .= "<li><a href='$explode[0]$final$start'>$start</a><li>";
}
On pagination controls how do I get the active class to work.
The CSS style for a:active is not showing up (everything else seems fine on the controls).
Pagination Code:
//start pagination
//Get the total count of rows.
$sql = "SELECT COUNT(id) FROM users";
$query = mysqli_query($dbc, $sql);
$row = mysqli_fetch_row($query);
//Here we have the total row count
$rows = $row[0];
//Number of results to show per page
$page_rows = 21;
//This tells us the page number of our last page
$last = ceil($rows/$page_rows);
//This makes sure last cannot be less than 1
if($last < 1){
$last = 1;
}
//establish the $pagenum variable
$pagenum = 1;
//Get pagenum from URL vars if it is present, else it is = 1
if(isset($_GET['pn'])){
$pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
//This makes sure the page number isn't below 1 or more than our $last page
if($pagenum < 1){
$pagenum = 1;
} else if($pagenum > $last) {
$pagenum = $last;
}
//This sets the range of rows to query for the chosen $pagenum
$limit = 'LIMIT ' . ($pagenum - 1) * $page_rows .',' .$page_rows;
//This is your query again, it is for grabbing just one page worth of rows by applying the limit variable
$sql = "SELECT id, image, fname, surname, address FROM users ORDER BY id DESC $limit";
$query = mysqli_query($dbc, $sql);
//This shows the user what page they are on and the total number of pages
$textline1 = "<b>$rows</b> Users";
$textline2 = "Page <b>$pagenum</b> of <b>$last</b>";
//$paginationCrls variable
$paginationCtrls = ' ';
//if there is more than 1 page worth of results
if($last != 1){
/*First we check if we are on page one. If we are then we don't need a link to the previous page or the first page so we do nothing. If we aren't then we generate links to the first page and to the previous page.*/
if($pagenum > 1){
$previous = $pagenum - 1;
$paginationCtrls .= '« Previous ';
//Render clickable number links that should appear on the left of the target page number
for($i = $pagenum-4; $i < $pagenum; $i++){
if($i > 0) {
$paginationCtrls .= ''.$i.' ';
}
}
}
//Render the target page number, but without it being a link
$paginationCtrls .= ''.$pagenum.' ';
//Render clickable number links that should appear on the right of the target page number
for($i = $pagenum+1; $i <= $last; $i++){
$paginationCtrls .= ''.$i.' ';
if($i >= $pagenum+4){
break;
}
}
//This adds the same as above only checking if if we are on the last page and then generating Next
if($pagenum != $last){
$next = $pagenum + 1;
$paginationCtrls .= ' Next » ';
}
}
//Finish Pagination
CSS Code:
div#pagination_controls a:active{
border: 1px solid #C00;
background-color: #C00;
color: #3f3f3f;
border-radius: 2px;
-moz-border-radius: 2px;
-webkit-border-radius: 2px;}
Your active page doesn't render as a link. Try changing these lines:
//Render the target page number, but without it being a link
$paginationCtrls .= ''.$pagenum.' ';
to
//Render the target page number, but without it being a link
$paginationCtrls .= '<span class="active">'.$pagenum.'</span> ';
and
div#pagination_controls a:active
{
border: 1px solid #C00;
background-color: #C00;
color: #3f3f3f;
border-radius: 2px;
-moz-border-radius: 2px;
-webkit-border-radius: 2px;
}
to
div#pagination_controls span.active
{
border: 1px solid #C00;
background-color: #C00;
color: #3f3f3f;
border-radius: 2px;
-moz-border-radius: 2px;
-webkit-border-radius: 2px;
}
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.