Limit Pagination Numbers For Huge Databases - php

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.

Related

How to display stars (1 to 5) from the value present in database

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>

PHP pagination script - duplicate [duplicate]

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

Reduce length of bootstrap pagination buttons

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

PHP Pagination Controls Style

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

Pagination in HTML code embeded in PHP

I want to add pagination to the script below which searches the database and outputs the images in a folder into rows and columns. But I want the output to be in pages, not all on the same page. How can I do it?
<?php
echo '<table border="0" cellpadding="15" cellspacing="15">';
$getImages = mysql_query("SELECT * FROM yaamembers");
if(!$getImages)
die("Cannot execute query. " . mysql_error());
$countRows = mysql_num_rows($getImages);
$i = 0;
if ($countRows > 0)
{
while ($row_rsYaamembers = mysql_fetch_assoc($getImages))
{
if ($i % 3 == 0) echo ($i > 0? '</tr>' : '') . '<tr>';
echo '<td valign="top"><a target="_blank" href="yimagelarge.php?yaaid=' . $row_rsYaamembers['yaaID'] . '"><img src="/home/youngatart/yaamembers/'.$row_rsYaamembers['photo'].'" border="0" width="120" /></td>';
if ($i == $countRows - 1)
echo '</tr>';
$i++;
}
}
echo '</table>';
?>
I have modified the code and I get three rows of three columns of images and the last row on the page filled with one image. This is the same for all the pages generated by the pagination links. Its supposed to fill up evenly before going to the next page. What could i be doing wrong?
Modified code below:
<?Php
$getImages = mysql_query("SELECT * FROM yaamembers");
if(!$getImages)
die("Cannot execute query. " . mysql_error());
$output = "";
$getImages = get_images($start,$limit);
if ($getImages && mysql_num_rows($getImages) > 0)
{
/* Pagination section2 */
$getAllImages = get_images();
$total_items = mysql_num_rows($getAllImages);
$paginate = paginate($targetpage,$total_items,$limit,$pagenum);
$paginate = trim($paginate);
/* Pagination section2 End */
echo '<table border="0" cellpadding="15" cellspacing="15">';
$countRows = mysql_num_rows($getImages);
$i = 0;
if ($countRows > 0)
{
while ($row_rsYaamembers = mysql_fetch_assoc($getImages))
{
if ($i % 3 == 0) echo ($i > 0) . '<tr>';
echo '<td valign="top"><a target="_blank" href="yimagelarge.php?yaaid=' . $row_rsYaamembers['yaaID'] . '"><img src="http://localhost/youngatart/yaamembers/'.$row_rsYaamembers['photo'].'" border="0" width="120" /></a><div id="text2"><div class="clear_4"></div><div align="center" id="text2"><a target="_blank" href="yimagelarge.php?yaaid=' . $row_rsYaamembers['yaaID'] . '"><div align="center" id="text2"> '.$row_rsYaamembers['school'].'</a></div><div class="clear_4"></div><div align="center" id="text2"><a target="_blank" href="yimagelarge.php?yaaid=' . $row_rsYaamembers['yaaID'] . '"> '.$row_rsYaamembers['year'].'</a></div></div></td>';
if ($i == $countRows - 1)
echo '</tr>';
$i++;
}
}
echo '</table>';
$output .= $paginate;
}
echo $output;
?>
I suggest a simple change in your script, to make it comfortable for my explanations (because I'm not a good programmer! :) ). Also, I have created some functions to work with.
Suggested changes
Make some changes in HTML (use div and put a CSS class, and play
with CSS)
Make the get_images as a function
How to use
function get_images($start=0,$limit=0)
{
mysql_connect("host","user","pass")or die("Cannot connect DB");
mysql_select_db("db_name")or die("DB does not exist");
$sql = "SELECT * FROM yaamembers";
if($start!=0 || $limit!=0)
{
$sql .= " LIMIT ". $start .", ". $limit;
}
$sql .= ";";
$data = mysql_query($sql);
mysql_close();
return $data;
}
/* Pagination section1 */
$pagenum = 1;
$limit = 10; /* Items per page*/
$start = 0;
if(isset($_GET['pagenum'])) {
$pagenum = $_GET['pagenum'];
}
$url = get_current_url();
$targetpage = format_url($url, "pagenum");
if($pagenum)
{
$start = ($pagenum - 1) * $limit;
}
/* Pagination section1 End */
$output = "";
$getImages = get_images($start,$limit)
if ($getImages && mysql_num_rows($getImages) > 0)
{
/* Pagination section2 */
$getAllImages = get_images();
$total_items = mysql_num_rows($getAllImages);
$paginate = paginate($targetpage,$total_items,$limit,$pagenum);
$paginate = trim($paginate);
/* Pagination section2 End */
while ($row_rsYaamembers = mysql_fetch_assoc($getImages))
{
$output .= "
<div>
<a target="_blank" href="yimagelarge.php?yaaid=' . $row_rsYaamembers['yaaID'] . '">
<img src="/home/youngatart/yaamembers/'.$row_rsYaamembers['photo'].'" border="0" width="120" />
</a>
</div>";
}
$output .= $paginate;
}
echo $output;
Here follows the functions to paginate
<?php
function paginate($targetpage,$total_items=0,$limit=10,$pagenum=1)
{
/*
* Remember to remove pagenum variable from $targetpage variable
*/
$adjacents = 3; /* How many items adjascent to page link */
/* How many items to show per page $limit = 30; */
/* Setup page vars for display. */
if ($pagenum == 0)
$pagenum = 1; /* If no page var is given, default to 1. */
$prev = $pagenum - 1; /* Previous page is page - 1 */
$next = $pagenum + 1; /* Next page is page + 1 */
$lastpage = ceil($total_items/$limit); /* Last page is equal to total pages / items per page, rounded up. */
$lpm1 = $lastpage - 1; /* Last page minus 1 */
/*
Now we apply our rules and draw the pagination object.
We're actually saving the code to a variable in case we want to draw it more than once.
*/
$pagination = "";
if($lastpage > 1)
{
$pagination .= "<div class=\"pagination\">";
/* previous button */
if ($pagenum > 1)
{
$pagination .= "Previous";
}
else
{
$pagination .= "<span class=\"disabled\">Previous</span>";
}
/* Pages */
if ($lastpage < 7 + ($adjacents * 2)) /* Not enough pages to bother breaking it up. */
{
for ($counter = 1; $counter <= $lastpage; $counter++)
{
if ($counter == $pagenum)
{
$pagination .= "<span class=\"current\">$counter</span>";
}
else
{
$pagination .= "$counter";
}
}
}
elseif($lastpage > 5 + ($adjacents * 2)) /* Enough pages to hide some */
{
/* Close to beginning; only hide later pages */
if($pagenum < 1 + ($adjacents * 2))
{
for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
{
if ($counter == $pagenum)
{
$pagination .= "<span class=\"current\">$counter</span>";
}
else
{
$pagination .= "$counter";
}
}
$pagination .= "...";
$pagination .= "$lpm1";
$pagination .= "$lastpage";
}
/* In middle; hide some front and some back */
elseif($lastpage - ($adjacents * 2) > $pagenum && $pagenum > ($adjacents * 2))
{
$pagination .= "1";
$pagination .= "2";
$pagination .= "...";
for ($counter = $pagenum - $adjacents; $counter <= $pagenum + $adjacents; $counter++)
{
if ($counter == $pagenum)
{
$pagination .= "<span class=\"current\">$counter</span>";
}
else
{
$pagination .= "$counter";
}
}
$pagination .= "...";
$pagination .= "$lpm1";
$pagination .= "$lastpage";
}
/* close to end; only hide early pages */
else
{
$pagination .= "1";
$pagination .= "2";
$pagination .= "...";
for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
{
if ($counter == $pagenum)
{
$pagination .= "<span class=\"current\">$counter</span>";
}
else
{
$pagination .= "$counter";
}
}
}
}
/* Next button */
if ($pagenum < $counter - 1)
{
$pagination .= "next";
}
else
{
$pagination .= "<span class=\"disabled\">next</span>";
}
$pagination .= "</div>\n";
}
return $pagination;
}
function format_url($url, $fileds)
{
/*-To remove queries from URL, the field input may be single string or an array of strings. */
$url_filed_array = explode("&",$url);
$return_url = '';
for($i=0; $i<count($url_filed_array); $i++)
{
if(is_array($fileds))
{
if($i==0)
{
$_url = explode('?',$url_filed_array[$i]);
$return_url .=$_url[0] .'?';
$url_filed = explode('=',$_url[1]);
}
else
{
$url_filed = explode('=',$url_filed_array[$i]);
}
if(!in_array($url_filed[0],$fileds))
{
if($i==0 && isset($_url[1]))
{
$return_url .=$_url[1];
}
else
{
$return_url .=$url_filed_array[$i];
}
if(($i+1) != count($url_filed_array))
{
$return_url .="&";
}
}
}
else
{
if($i==0)
{
$_url = explode('?',$url_filed_array[$i]);
$return_url .=$_url[0] .'?';
$url_filed = explode('=',$_url[1]);
}
else
{
$url_filed = explode('=',$url_filed_array[$i]);
}
if($url_filed[0]!=$fileds)
{
if($i==0 && isset($_url[1]))
{
$return_url .=$_url[1];
}
else
{
$return_url .=$url_filed_array[$i];
}
if(($i+1) != count($url_filed_array))
{
$return_url .="&";
}
}
}
}
if(substr($return_url,-1)=='&')
{
$return_url = substr($return_url, 0, -1);
}
if(substr($return_url,-1)=='?')
{
$return_url = substr($return_url, 0, -1);
}
return $return_url;
}
function get_current_url()
{
$pageURL = (#$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
if ($_SERVER["SERVER_PORT"] != "80")
{
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
}
else
{
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
?>
CSS code
div.pagination {
padding:3px;
margin:3px;
text-align:center;
}
div.pagination span.disabled ,
div.pagination span.current ,
div.pagination a
{
background:url('../images/pagination_bg.jpg') #ffffff repeat-x right center;
height: 28px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
padding: 5px 8px;
margin-right: 8px;
color: #6B6868;
}
div.pagination a {
border: 1px solid #ddd;
text-decoration: none;
}
div.pagination a:hover, div.pagination a:active {
border:1px solid #f2813a;
color: #f2813a;
background-color: #F46F1B;
}
div.pagination span.current {
border: 1px solid #f2813a;
font-weight: bold;
color: #FFF;
background:url('../images/pagination_bg_active.jpg') #F46F1B repeat-x right center;
}
div.pagination span.disabled {
border: 1px solid #f3f3f3;
color: #ccc;
}
div.pagination span.current,
div.pagination span.disabled {
cursor: default;
}
Create two background images as you like, in folder images:
pagination_bg.jpg /* Normal button image */
pagination_bg_active.jpg /* Active or current page button image */

Categories