PHP Problem: Position Numbers Are Not Showing Correctly - php

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.

Related

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

Use PHP while loop to create advance filter

I have a problem and that is I want to create a link on a website like people can click the link to show certain products only depending on percentage. like for example, i have a column in my database with discount percentage and it will show min discount and max discount. assuming we have min and max discount. $min=12 and $max=94; and I want to put them in links to show only products with certain discounts only like filtering. below is the example of the link.
<a href="#">12% to 20%</a
21% to 30%
31% to 40% and so on until it reaches
81% to 90% and the last will be
91% to 94%
smallest and largest numbers will be coming from a column from database and they can change frequently. i came up with solution and its working fine but my code is too long and its like I took to many steps which could be done in few lines of code. I have pasted my working code below but I am sure this can be reduced to few lines of code.
$catsql25 = "SELECT MAX(down_percentage) as largest FROM hot_deals";
$catquery25 = mysqli_query($conn, $catsql25);
while ($row25 = mysqli_fetch_array($catquery25, MYSQLI_ASSOC)){
$largest_number = $row25['largest'];
}
$catsql26 = "SELECT MIN(down_percentage) as smallest FROM hot_deals";
$catquery26 = mysqli_query($conn, $catsql26);
while ($row26 = mysqli_fetch_array($catquery26, MYSQLI_ASSOC)){
$smallest_number = $row26['smallest'];
}
$array_tens = array(10,20,30,40,50,60,70,80,90,100);
foreach ($array_tens as $value){
if(($value - $smallest_number <= 10) && ($value - $smallest_number > 0)){
echo '<a href="/exp.php?fst='.$smallest_number.'&lst='.$value.'"><div class="lfmen2">';
echo $smallest_number." to ".$value."</div></a>";
$next_num = $value + 1;
$next_ten = 9;
$stop_num = floor($largest_number / 10);
$stop_num2 = $stop_num * 10;
//echo $stop_num2.'<br>';
$num_rounds = $stop_num2 - $value;
$num_rounds2 = $num_rounds / 10;
//echo $num_rounds2;
for ($i = 1; $i <= $num_rounds2; $i++){
$end_num = $next_num + $next_ten;
echo '<a href="/exp.php?fst='.$next_num.'&lst='.$end_num.'"><div class="lfmen2">';
echo $next_num;
echo " to ";
echo $end_num;
echo "</div></a>";
$next_num += 10;
$end_num += 10;
}
}
}
foreach ($array_tens as $value2){
if(($largest_number - $value2 < 10) && ($largest_number - $value2 > 0)){
$lsst = $value2 + 1;
if($lsst != $largest_number){
echo '<div class="lfmen2">'.$lsst." to ".$largest_number."</div>";
}
elseif($lsst == $largest_number){
echo '<div class="lfmen2">'.$largest_number.'</div>';
}
}
}
I know its all mess but..
Thanks.
First thing you could do is only one SQL Query :
$catsql = "SELECT MAX(down_percentage) as largest, MIN(down_percentage) as smallest FROM hot_deals";
And then you'll need only one loop :
$catquery = mysqli_query($conn, $catsql);
while ($row = mysqli_fetch_array($catquery, MYSQLI_ASSOC)){
$largest_number = $row['largest'];
$smallest_number = $row['smalest'];
}
After that, you could make only one foreach loop. The two "if" conditions could be in the same loop :
foreach ($array_tens as $value) {
if (($value - $smallest_number <= 10) && ($value - $smallest_number > 0)) {
echo '<a href="/exp.php?fst='.$smallest_number.'&lst='.$value.'"><div class="lfmen2">';
echo $smallest_number." to ".$value."</div></a>";
$next_num = $value + 1;
$next_ten = 9;
$stop_num = floor($largest_number / 10);
$stop_num2 = $stop_num * 10;
//echo $stop_num2.'<br>';
$num_rounds = $stop_num2 - $value;
$num_rounds2 = $num_rounds / 10;
//echo $num_rounds2;
for ($i = 1; $i <= $num_rounds2; $i++) {
$end_num = $next_num + $next_ten;
echo '<a href="/exp.php?fst='.$next_num.'&lst='.$end_num.'"><div class="lfmen2">';
echo $next_num;
echo " to ";
echo $end_num;
echo "</div></a>";
$next_num += 10;
$end_num += 10;
}
}
if (($largest_number - $value < 10) && ($largest_number - $value > 0)) {
$lsst = $value + 1;
if ($lsst != $largest_number) {
echo '<div class="lfmen2">'.$lsst." to ".$largest_number."</div>";
} elseif ($lsst == $largest_number) {
echo '<div class="lfmen2">'.$largest_number.'</div>';
}
}
}
To make it more readable, you could also comment your code to know what do what.
This and a good indentation and you're right.
Hope it helps.

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

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.

Generate gallery loop

The Problem
I'm attempting to generate a gallery where it will display 3 "blocks" per row and alternate between large and small images.
For example:
Big | 4 Small | Big
4 Small | Big | 4 Small
One big image is the size of 4 small images.
What I've Tried
Here's an example of what I've tried so far.
$i = 0;
$r = 0;
$image = '';
foreach($gallery_images as $image_data) {
($i == 5 ? $i = 0 : '');
//If there's been 3 blocks added to the row, end the row and start a new one
if($r == 3) { $image .= '</div>'; $r = 0; }
//Start new row every 3 blocks
if($r == 0) { $image .= '<div class="row">'; }
//One big image, per 4 small in sequence
if($i == 0) {
$image .= '<div style="height: 300px; width:33.3%; background: red;float:left;"></div>';
++$r;
} else {
//If no small, start the block
if($i == 1) { $image .= '<div style="width:33.3%;height:300px;float:left;">'; }
//echo each small image
$image .= '<div style="height: 150px; width:50%;background: blue;float:left;"></div>';
//Once 4 images have been echoed, close the div
if($i == 4) { $image .= '</div>'; ++$r; }
}
++$i;
}
echo $image;
The first row displays fine, but then the next row messes up completely. I just can't see what I've missed in order for this to work.
The class of "row" is because I'm building this upon the foundation framework by Zurb in order to make it responsive.
The issue is that on the 2nd row(s), you do not increment $r to 1 until the end of the 4 small, so it continues to add <div class="row"> before each small image. You need to change your if block on the even rows. You can do this by adding 1 more counter, that keeps track of what row you are on -
by adding
$t=0;
and changing
//Start new row every 3 blocks
if($r == 0) { $image .= '<div class="row">'; }
to
//Start new row every 3 blocks
if($t%2==1){ // if we are on an even row
if($i == 1 && $r == 0) { $image .= '<div class="row">';}
}
else{ // if we are on an odd row
if($r == 0) { $image .= '<div class="row">'; }
}
you now have-
$i = 0;
$r = 0;
$image = '';
$t=0; // counter for odd/even row
foreach($gallery_images as $image_data) {
($i == 5 ? $i = 0 : '');
//If there's been 3 blocks added to the row, end the row and start a new one
if($r == 3) { $image .= '</div>'; $r = 0; ++$t; }
//Start new row every 3 blocks
if($t%2==1){ // if we are on an even row
if($i == 1 && $r == 0) { $image .= '<div class="row">';} // if it is the first small image group start the row
}
else{ // if we are on an odd row
if($r == 0) { $image .= '<div class="row">'; } // if it is the first large image
}
//One big image, per 4 small in sequence
if($i == 0) {
$image .= '<div style="height: 300px; width:33.3%; background: red;float:left;"></div>';
++$r;
} else {
//If no small, start the block
if($i == 1) { $image .= '<div style="width:33.3%;height:300px;float:left;">'; }
//echo each small image
$image .= '<div style="height: 150px; width:50%;background: blue;float:left;"></div>';
//Once 4 images have been echoed, close the div
if($i == 4) { $image .= '</div>'; ++$r; }
}
++$i;
}
echo $image;
you can see a phpFiddle example at http://phpfiddle.org/main/code/t25-kbe This is with 60 images, so there is 4 rows total, 2 of each pattern.
NEW ANSWER:
Ok this is how you wanted it:
<style type="text/css">
.big {
width:200px;
height:200px;
background:#03F;
}
.small {
width:50px;
height:50px;
background:#F00;
}
</style>
<?
$gallery_images = array(
1,2,3,4,5,6
);
echo '<div class="row">';
//count counts whether it's big or small
$count = 0;
//count2 counts whether it's the end of the row or not
$count2 = 0;
$row = 0;
foreach($gallery_images as $image_data) {
//assign these from image data
$big = "<img class='big'>";
$small = array(
"<img class='small'>","<img class='small'>","<img class='small'>","<img class='small'>"
);
//if it's 0 it's big else it's 1 and it's small
if($count === 0) {
echo $big;
$count++;
}else {
foreach($small as $s) {
echo $s;
};
$count = 0;
}
//if it's 2 then its the end of the row else increment
if($count2 === 2) {
echo "</div>";
echo "<div class='row'>";
$count2 = 0;
}else {
$count2 ++;
}
}
?>
NEW:
Ok you'd need to tinker with this, but I think it solves the issue:
<style type="text/css">
.big {
width:200px;
height:200px;
background:#03F;
}
.small {
width:50px;
height:50px;
background:#F00;
}
</style>
<?
$gallery_images = array(
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
);
//find out how many images
$total_images = count($gallery_images);
echo '<div class="row">';
//count counts whether it's big or small
$count = 0;
//count2 counts whether it's the end of the row or not
$count2 = 0;
$row = 0;
//overall count of images
$overall = 0;
for($i=0;$i<count($gallery_images);$i++) {
//assign these from image data
$big = "<img class='big' src='".$gallery_images[$i]."'>";
//increment overall
$overall++;
if($i+1 < $total_images) {
$small1 = $i+1;
$small[] = $small1; //would be $gallery_images[$small1]
$overall++;
}
if($i+1 < $total_images) {
$small2 = $i+2;
$small[] = $small2; //would be $gallery_images[$small2]
$overall++;
}
if($i+1 < $total_images) {
$small3 = $i+3;
$small[] = $small3; //would be $gallery_images[$small3]
$overall++;
}
if($i+1 < $total_images) {
$small4 = $i+4;
$small[] = $small4; //would be $gallery_images[$small4]
$overall++;
}
//if it's 0 it's big else it's 1 and it's small
if($count === 0) {
if($overall < $total_images) {
echo $big;
$count++;
}
}else {
if($small) {
foreach($small as $s) {
echo "<img class='small' src='".$s."' />";
};
$count = 0;
}
}
if($count2 === 2) {
echo "</div>";
echo "<div class='row'>";
$count2 = 0;
}else {
$count2 ++;
}
unset($small);
if($overall >= $total_images) {
echo "</div>";
}
}
?>

Categories