The code I have works absolutely perfectly:
<?
$maxresults = 10;
$total = $row[total];
$pagecount = $total / $maxresults;
if (!isset($_GET['page'])) { $_GET['page'] = '1'; }
$startcount = (($_GET['page'] - 1) * $maxresults + 1);
$stopcount = $startcount + ($maxresults - 1);
$lastTime = null;
$i='0';
$sc = $startcount;
$stmt=$db->prepare("// SELECT STATEMENT");
$stmt->bindParam(':user', $username);
$stmt->execute();
while ( $row = $stmt->fetch() ) {
if (!($sc > $stopcount)) {
$i++;
if( $row['time'] !== $lastTime ) {
if ( $lastTime === NULL ) {
echo '// close of loop';
} else {
echo '// loop grouping as title';
}
$lastTime = $row['time'];
}
if ($i >= $sc) { ?>
// the html to loop
<?
$sc++;
}
}
}
?>
Forward and Back buttons are easy enough to create. if $_GET['page'] * 10 > $total, active the next button, if $_GET['page'] > 1 activate previous button.
What I can't figure out is the correct formula and loop so I can always display the correct number of "page numbered" links. I want to always show 5 based on the 3rd number. So 1 would should 5 links: 1 - 5, 2 would also show 1 - 5, as would 3, 4 would show 2 - 6, 5 would show 3 - 7.
Now obviously, I could just add 2 and subtract 2 from the current $_GET[page] if the get page is greater than 3, but I need to take into account testing to see if the results go that high. So only if results are greater than 10 should number 2 show, and then if on page 16 pages 17 and 18 should only show if there are 170 and 180 results to display.
Perhaps I have just been staring at the code to long, but I can't seem to get a formula or loop correct in my head to even attempt the code page.
It was a fairly specific question. Wasn't sure if anyone would help with something so specific or not. Guess I learned.
Here is the answer to my own question:
<ul>
<li class="<? if ($_GET['page'] < '2') { echo 'disabled' ; } ?>">
<a href="<?
if ($_GET['page'] == '2') {
echo 'inbox.php';
} else {
echo '?page='.($_GET[page] - 1);
}
?>">Prev</a>
</li> <!-- previous button-->
<li style="<? if ($_GET['page'] - 2 < '1') { echo 'display:none;'; } ?>">
<a href="?page=<?
echo ($_GET[page] -2); ?>">
<? echo ($_GET[page] -2); ?>
</a>
</li> <!-- the button 2 before current spot if its greater than 0 -->
<li style="<? if ($_GET['page'] - 1 < '1') { echo 'display:none;'; } ?>">
<a href="?page=<?
echo ($_GET[page] -1); ?>">
<? echo ($_GET[page] -1); ?>
</a>
</li> <!-- the button 1 before current spot if its greater than 0 -->
<li class="disabled">
<? echo $_GET[page]; ?>
</li> <!-- current button disabled -->
<li style="<? if ($total - ($_GET[page] * 10) <= '0') { echo 'display:none;'; } ?>">
<a href="?page=<?
echo ($_GET[page] + 1); ?>">
<? echo ($_GET[page] +1); ?>
</a>
</li> <!-- the button 1 after current spot if results go that high -->
<li style="<? if ($total - ($_GET[page] + 1) * 10 <= '0') { echo 'display:none;'; } ?>">
<a href="?page=<?
echo ($_GET[page] + 2); ?>">
<? echo ($_GET[page] + 2); ?>
</a>
</li> <!-- the button 2 after current spot if results go that high -->
<li class="<? if ($total - ($_GET[page] * 10) <= '0') { echo 'disabled'; } ?>">
Next
</li> <!-- the next button if results go that high -->
</ul>
#bruce after seeing your solution, I'd like to give you my own solution.
$page = $_GET['page'];
$max_pages = ceil($total / $maxresults);
$min_pages = 1;
$start = max($min_pages, $page-2);
$end = min($max_pages, $start+2);
$nav = ($page > $min_pages ? '<li><</li>' : '' );
for ($i = $start; $i <= $end; $i++)
$nav .= '<li' . ($i == $page ? 'class="active"' : '' ) . '>' . $i . '</li>';
$nav .= ($page < $max_pages ? '<li>></li>' : '' );
Related
I'm trying to code pagination and it should show this:
<<1...11>>
but instead it shows this:
<<-5...11>>
This happens if the content less than 11 pages.
this is my code
<?php if($page != 1): ?>
<a href="?page=<?php echo $page-1; ?>&srch-term=<?php echo #$_GET['srch-term']; ?>&tag=<?php echo #$_GET['tag']; ?>&color=<?php echo #$_GET['color']; ?>" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
<?php else: ?>
<span aria-hidden="true">«</span>
<?php endif; ?>
</li>
<?php
$limitPage = 5;
$fromPage = ($page - $limitPage) <= 0 ? 1:$page - $limitPage;
$endPage = ($page + $limitPage) >= $count? $count:$page+$limitPage;
if($page <= ($limitPage)) $endPage = ($limitPage*2) + 1;
if(($page - $limitPage) > ($count - ($limitPage*2))) $fromPage = $count - ($limitPage*2);
?>
<?php for($i=$fromPage;$i<=$endPage;$i++): ?>
<li class="<?php echo ($page == $i)? 'active':''; ?>"><?php echo $i; ?></li>
<?php endfor; ?>
<li class="<?php echo ($page == $count)? 'disabled':''; ?>">
<?php if($page != $count): ?>
<a href="?page=<?php echo $page+1; ?>&srch-term=<?php echo #$_GET['srch-term']; ?>&tag=<?php echo #$_GET['tag']; ?>&color=<?php echo #$_GET['color']; ?>" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
<?php else: ?>
<span aria-hidden="true">»</span>
<?php endif; ?>
Looks like this is the line that is not working the way you expect.
if(($page - $limitPage) > ($count - ($limitPage*2))) $fromPage = $count - ($limitPage*2);
Here is a php sandbox link with some debugging code that should help you out. http://sandbox.onlinephpfunctions.com/code/df2faac69d217ce8e5bea86b63325b8dd4c49600
$limitPage = 5;
$page = 1;
$count = 5;
$fromPage = ($page - $limitPage) <= 0 ? 1:$page - $limitPage;
$endPage = ($page + $limitPage) >= $count? $count:$page+$limitPage;
echo $fromPage . ' ' . $endPage. "\n";
if($page <= ($limitPage)) $endPage = ($limitPage*2) + 1;
echo $fromPage . ' ' . $endPage. "\n";
if(($page - $limitPage) > ($count - ($limitPage*2))) $fromPage = $count - ($limitPage*2);
echo $fromPage . ' ' . $endPage;
I want to calculate average rating of all heading. I have 6 heading under one person and every person have 5 star. I want to show over all rating (e.g 4.2 or 4 )
Here is my code
<li><p>Overall Experience</p>
<?php
$starsLeft = 5 - $count_all_guest_star[0]->overall_experience_star;
if($count_all_guest_star[0]->overall_experience_star>0):
for( $i=1; $i<= $count_all_guest_star[0]->overall_experience_star; $i++)
{ ?>
<img src="<?php echo base_url(); ?>assets/img/on-stars.gif"/>
<?php
}
endif;
if ($starsLeft > 0) { // if there are any more stars left
for ($i = 1; $i <= $starsLeft; $i++) { // go through each remaining star
// show it empty
?>
<img src="<?php echo base_url(); ?>assets/img/off-stars.gif"/>
<?php }
}
?>
</li>
<li><p>Communication</p>
<?php
$com_starsLeft = 5 - $count_all_guest_star[0]->communication_star;
if( $count_all_guest_star[0]->communication_star > 0):
for( $j=1; $j<= $count_all_guest_star[0]->communication_star; $j++)
{
?>
<img src="<?php echo base_url(); ?>assets/img/on-stars.gif"/>
<?php
}
endif;
if ($com_starsLeft > 0) { // if there are any more stars left
for ($i = 1; $i <= $com_starsLeft; $i++) { // go through each remaining star
// show it empty
?>
<img src="<?php echo base_url(); ?>assets/img/off-stars.gif"/>
<?php }
}
?></li>
$AverageRating = ((1*$starsLeft)+(2*$com_starsLeft)+(3*$acc_starsLeft)+(4*$clean_starsLeft)+(5*$pick_starsLeft) + (6*$pick_starsLeft))/6;
echo '$AverageRating';
kindly advice me any solution.
I think you can compute the average like this
$avg = ($count_all_guest_star[0]->overall_experience_star +
$count_all_guest_star[0]->communication_star +
$count_all_guest_star[0]->heading3 +
$count_all_guest_star[0]->heading4 +
$count_all_guest_star[0]->heading5 +
$count_all_guest_star[0]->heading6) / 6;
You can then use the same method to display stars.
$avg_stars_left = 5 - $avg;
<?php
$host='localhost';
$user='root';
$password='root';
$database='database';
$startindex=#$_REQUEST['seek'];
$db=mysql_connect($host, $user, $password)
or die ("Impossibile connettersi al server $host");
mysql_select_db($database, $db)
or die ("Impossibile connettersi al database $database");
$query="SELECT * FROM ordini_master";
$dbResult=mysql_query($query, $db);
$AffectedRows=mysql_affected_rows($db);
mysql_data_seek($dbResult, $startindex);
$row=mysql_fetch_row($dbResult);
foreach($row as $k=>$v)
{
$myfield=mysql_fetch_field($dbResult, $k);
print($myfield->name . " : $v <br/>");
}
mysql_free_result($dbResult);
mysql_close($db);
print("<br/>Seleziona il record<br/>");
for($index=0; $index<$AffectedRows; $index++)
{
print("<a href=\"{$_SERVER['PHP_SELF']}?seek=$index\" >" .
($index+1) . "</a> ");
}
?>
This code allow the navigation between a query records, so it create a page foreach record in database and so shows one record time. How can i modify that code to paging every 10 records? So i want to show 10 records time and create a page for the next.
Sorry for my english (I'm italian) , i hope you can help me.
What you need first is the LIMIT statement from mysql. MySql states:
The LIMIT clause can be used to constrain the number of rows returned
by the SELECT statement. LIMIT takes one or two numeric arguments,
which must both be nonnegative integer constants (except when using
prepared statements).
With two arguments, the first argument specifies the offset of the
first row to return, and the second specifies the maximum number of
rows to return. The offset of the initial row is 0 (not 1):
As for how to implement it in your code I could not have written a better answer as the one found here.
Use LIMIT to get as many records as you wish.
Example:
SELECT * FROM tbl LIMIT 5,10; # Retrieve rows 6-15
Here is your modified code. This should work for your.
I haven't tested it but give it a try:
<?php
$host='localhost';
$user='root';
$password='root';
$database='database';
$startindex=(isset($_REQUEST['seek']) ? $_REQUEST['seek'] : 0);
$db=mysql_connect($host, $user, $password)
or die ("Impossibile connettersi al server $host");
mysql_select_db($database, $db)
or die ("Impossibile connettersi al database $database");
$queryCnt = "SELECT count(*) as cnt FROM ordini_master";
$CntRow=mysql_fetch_row(mysql_query($query, $db));
$CntData = $CntRow[0];
$step = 10;
$query="SELECT * FROM ordini_master LIMIT $startindex, $step";
$result=mysql_query($query, $db);
while ($row = mysql_fetch_assoc($result)) {
foreach($row as $k=>$v) {
$myfield=mysql_fetch_field($result, $k);
print($myfield->name . " : $v <br/>");
}
}
mysql_free_result($result);
mysql_close($db);
print("<br/>Seleziona il record<br/>");
for($index=0; $index<$CntData; $index=$index+$step) {
print("<a href=\"{$_SERVER['PHP_SELF']}?seek=$index\" >" .
($index+1) . "</a> ");
}
Use the information from tadman too.
It's very important to do something to prevent SQL injection and it's also necessary to use PDO or the mysqli extension because the mysql extension will not longer be supported.
You can use COUNT to display your records and create pages
function getLimitData($start,$limit){
//getting all items
$db = new PDO('mysql:host=localhost; dbname=data','root','');
$results = $db->query("SELECT * FROM table ORDER BY ID DESC limit $start,$limit");
$results = $results->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
//database connection
$db = new PDO('mysql:host=localhost; dbname=data','root','');
//pagination pages
$nav_counter = basename($_SERVER['SCRIPT_FILENAME']);
$page_counter = $nav_counter;
$nav_counter = rtrim($nav_counter, ".php");
$cPage = $page_counter + 1;
//creating next pages
$first_next = $nav_counter + 1 ;
$sec_next = $first_next + 1 ;
$third_next = $sec_next + 1 ;
$fourth_next = $third_next + 1 ;
$fifth_next = $fourth_next + 1 ;
$sixth_next = $fifth_next + 1 ;
$seventh_next = $sixth_next + 1 ;
$next_page = $seventh_next + 1;
//creating previous pages
$first_prev = $nav_counter - 1 ;
$sec_prev = $nav_counter - 2 ;
$third_prev = $nav_counter - 3 ;
$fourth_prev = $nav_counter - 4 ;
$fifth_prev = $nav_counter - 5 ;
$sixth_prev = $nav_counter - 6 ;
$seventh_prev = $nav_counter - 7 ;
//row count
$tableExists = $db->tableExist();
$ROW_COUNT = $db->getRowCount();
$numRows= 9; //number of items to be displayed
//last page
//last page
$last_page = ($ROW_COUNT / $numRows) - 1;
if(!is_int($last_page)){
$last_page = (int)$last_page + 1;
}
$pageNate = '';
if($ROW_COUNT <= $numRows){
$pageNate = 'class="hide"';
}else{
$pageNate = 'class="exist"';
}
//displaying torrents
$start = 0;
$limit = $numRows;
if ($page_counter !== 'index.php') {
$start = ($limit * $nav_counter);
}
//getting number of rows left in the table
$rows_left = $db->getLimitData($start, $limit);
$number_rows = 0;
foreach ($rows_left as $r) {
$number_rows = $number_rows + 1;
}
if ($number_rows < $numRows) {
$limit = $number_rows;
}
$items = $db->getLimitData($start, $limit);
?>
displaying item
<ol>
<?php foreach($items as $item) : ?>
<li><php echo $item['Value']; ?></li>
<?php endforeach; ?>
</ol>
pagination code
<?php
$pages = array();
for ($counter = 1; $counter <= $last_page; $counter++) {
$pages[] = $counter;
}
//storing pages in array and creating a page if it doesn't exist
foreach ($pages as $key) {
$page = $key.'.php';
//if page doesn't exists create page
if(file_exists($page)== false && $key <= $last_page){
copy('index.php', $page);
}
}
?>
<p class="pagenav" >
<a href="index.php" <?php if ($page_counter == 'index.php') {echo 'class="hide"';} ?>><<</a>
<a href="<?php if ($page_counter == '1.php') {echo 'index.php';}else{echo "$first_prev".".php";} ?>" <?php if ($page_counter == 'index.php') {echo 'class="hide"';} ?>><</a>
<a href="<?php echo "$seventh_prev".".php"; ?>" <?php if($seventh_prev <= 0){echo 'class="hide"';} ?>><?php echo $seventh_prev;?></a>
<a href="<?php echo "$sixth_prev".".php"; ?>" <?php if($sixth_prev <= 0){echo 'class="hide"';} ?>><?php echo $sixth_prev;?></a>
<a href="<?php echo "$fifth_prev".".php"; ?>" <?php if($fifth_prev <= 0){echo 'class="hide"';} ?>><?php echo $fifth_prev;?></a>
<a href="<?php echo "$fourth_prev".".php"; ?>" <?php if($fourth_prev <= 0){echo 'class="hide"';} ?>><?php echo $fourth_prev;?></a>
<a href="<?php echo "$third_prev".".php"; ?>" <?php if($third_prev <= 0){echo 'class="hide"';} ?>><?php echo $third_prev;?></a>
<a href="<?php echo "$sec_prev".".php"; ?>" <?php if($sec_prev <= 0){echo 'class="hide"';} ?>><?php echo $sec_prev;?></a>
<a href="<?php echo "$first_prev".".php"; ?>" <?php if($first_prev <= 0 ){echo 'class="hide"';} ?>><?php echo $first_prev;?></a>
<a <?php if ($page_counter == 'index.php') {echo 'class="hide"';}else{ echo 'id="here"';} ?>><?php echo $nav_counter; ?></a>
<a href="<?php echo $first_next.'.php'; ?>" <?php if($first_next <= $last_page){echo 'class="exist"';}else{echo 'class="hide"';} ?>><?php echo $first_next;?></a>
<a href="<?php echo "$sec_next".".php"; ?>" <?php if($sec_next <= $last_page){echo 'class="exist"';}else{echo 'class="hide"';} ?>><?php echo $sec_next;?></a>
<a href="<?php echo "$third_next".".php"; ?>" <?php if($third_next <= $last_page){echo 'class="exist"';}else{echo 'class="hide"';} ?>><?php echo $third_next;?></a>
<a href="<?php echo "$fourth_next".".php"; ?>" <?php if($fourth_next <= $last_page){echo 'class="exist"';}else{echo 'class="hide"';} ?>><?php echo $fourth_next;?></a>
<a href="<?php echo "$fifth_next".".php"; ?>" <?php if($fifth_next <= $last_page){echo 'class="exist"';}else{echo 'class="hide"';} ?>><?php echo $fifth_next;?></a>
<a href="<?php echo "$sixth_next".".php"; ?>" <?php if($sixth_next <= $last_page){echo 'class="exist"';}else{echo 'class="hide"';} ?>><?php echo $sixth_next;?></a>
<a href="<?php echo "$seventh_next".".php"; ?>" <?php if($seventh_next <= $last_page){echo 'class="exist"';}else{echo 'class="hide"';} ?>><?php echo $seventh_next;?></a>
<a href="<?php echo "$first_next".".php"; ?>" <?php if($first_next <= $last_page){echo 'class="exist"';}else{echo 'class="hide"';} ?>>></a>
<a href="<?php echo $last_page.'.php'; ?>" <?php if($nav_counter == $last_page){echo 'class="hide"';}else{echo 'class="exist"';} ?>>>></a>
</p>
I'd like to set the following up as a loop (so that the pattern is repeated every 5 elements). I've tried to read up on it and I believe I need to set it up as an array, but I have no idea where to start.
Here's my code:
<div class="ccm-page-list">
<?php
$i= 0;i;
foreach ($pages as $page):
$i++;
$title = $th->entities($page->getCollectionName());
$url = $nh->getLinkToCollection($page);
$target = ($page->getCollectionPointerExternalLink() != '' && $page->openCollectionPointerExternalLinkInNewWindow()) ? '_blank' : $page->getAttribute('nav_target');
$target = empty($target) ? '_self' : $target;
$description = $page->getCollectionDescription();
$description = $controller->truncateSummaries ? $th->shorten($description, $controller->truncateChars) : $description;
$description = $th->entities($description);
$img = $page->getAttribute('thumbnail');
$thumb = $ih->getThumbnail($img, 550, 550, true);
?>
<a href="<?php echo $url ?>" target="<?php echo $target ?>"> <div class="col-sm-4 grid-item">
<div class="item-img-blog" >
<img src="<?php echo $thumb->src ?>" width="auto" height="100%" alt="" />
<div <?php
if($i == 1) {
?>class="item-class-1" <?php }
if($i == 3) {
?>class="item-class-2" <?php }
if($i == 2) {
?>class="item-class-3" <?php }
if($i == 4) {
?>class="item-class-3" <?php }
if($i == 5) {
?>class="item-class-1" <?php }
?>>
<div class="text-container">
<h1><?php echo $description ?></h1>
<p><?php echo $date = $page->getCollectionDatePublic('d/m/Y'); ?></p>
</div>
</div>
</div>
</div></a>
<?php endforeach; ?>
</div>
I would really appreciate any help! Thanks in advance!
$i= 0;
$classes = array(1 => 1, 2 => 3, 3 => 2, 4 => 3, 5 => 1);
foreach ($pages as $page) {
$i++;
.....
echo 'class="item-class-'.$classes[$i % (count($classes) + 1)];
.....
}
You don't need an extra loop, you can use the modulo operator (aka, the remainder of a division) and some basic math to cope with the fact that you want to cycle 1->5:
$i= 0; // note that I removed the "i;" at the end of this line!
foreach ($pages as $page):
$cyclici = ($i % 5) + 1;
// then, use $cyclici everywhere you want to see that 1-5 1-5 pattern
...
if($cyclici == 1) {
...
// and increment $i at the *end* of the loop instead of the start.
$i++
endforeach;
EDITed to clarify the relationship between $i and $cyclici - $i is still incremented for each iteration of the loop, $cyclici is derived from that incrementing value to obtain the desired 1 2 3 4 5 1 2 3 4 5 ... sequence.
I have a page which get's populated dynamically from a Mysql database.
To prevent to much information been displayed at once, I have added pagination to page.
Using this code.
$currentPage = $_SERVER["PHP_SELF"];
$maxRows_atoz = 10; $page= 0;
if (isset($_GET['page'])) {$page= $_GET['page'];}
$startRow_atoz = $page* $maxRows_atoz;
mysql_select_db($database_main, $main);
$query_atoz = "SELECT * FROM main WHERE title LIKE 'A%'";
$query_limit_atoz = sprintf("%s LIMIT %d, %d", $query_atoz, $startRow_atoz, $maxRows_atoz);
$atoz = mysql_query($query_limit_atoz, $main) or die(mysql_error());
$row_atoz = mysql_fetch_assoc($atoz);
if (isset($_GET['totalRows_atoz'])) {$totalRows_atoz = $_GET['totalRows_atoz'];} else {$all_atoz = mysql_query($query_atoz); $totalRows_atoz = mysql_num_rows($all_atoz);}
$totalPages_atoz = ceil($totalRows_atoz/$maxRows_atoz)-1;
$queryString_atoz = ""; if (!empty($_SERVER['QUERY_STRING'])) {$params = explode("&", $_SERVER['QUERY_STRING']); $newParams = array(); foreach ($params as $param) {
if (stristr($param, "pageNum_atoz") == false && stristr($param, "totalRows_atoz") == false) {array_push($newParams, $param);}}
if (count($newParams) != 0) {$queryString_atoz = "&" . htmlentities(implode("&", $newParams));}}
$queryString_atoz = sprintf("&totalRows_atoz=%d%s", $totalRows_atoz, $queryString_atoz);
?>
<ul>
<li class="previous"> <?php if ($page > 0) { // Show if not first page ?>
<a title="See Previous 10 Results" href="<?php printf("?page=%d%s", $currentPage, max(0, $page - 1), $queryString_atoz); ?>">
<img src="/files/previous.png" /></a>
<?php } // Show if not first page ?></li>
<li class="next"> <?php if ($page < $totalPages_atoz) { // Show if not last page ?>
<a title="See Previous 10 Results" href="<?php printf("?page=%d%s", $currentPage, min($totalPages_atoz, $page + 1), $queryString_atoz); ?>">
<img src="/files/next.png" /></a>
<?php } // Show if not last page ?></li>
</ul>
The code works in paginaing the results, but has a limitation.
It currently only display's Next and Previous buttons.
I would like to add page numbers. This way a user can skip to 4th or 5th page in the result set rather than having to press the next button 4 or 5 times.
So, can some please tell me how I would go about doing this?
Thanks
I must say, I havent gone through the entire code of yours. You must indent your code to help others. If I get your question right, the following may help you. I haven't much taken care of finer details. This is just to give you an idea. :-)
<ul>
<li class="previous">
<?php if ($page > 0) { // Show if not first page ?>
<a title="See Previous 10 Results" href="<?php printf("?page=%d%s", $currentPage, max(0, $page - 1),$queryString_atoz); ?>">
<img src="/files/previous.png" /></a>
<?php } // Show if not first page ?></li>
<!--MODIFY_BEGIN-->
<li>
<?php for ($i=0;$i<$page; $i++){
if ($currentPage==$i)
echo ($currentPage+1);
else
echo "<a title='Page $i' href='?page=$i'>Page $i</a>";
} ?>
</li>
<!--MODIFY_END-->
<li class="next"> <?php if ($page < $totalPages_atoz) { // Show if not last page ?>
<a title="See Previous 10 Results" href="<?php printf("?page=%d%s", $currentPage, min($totalPages_atoz, $page + 1), $queryString_atoz); ?>">
<img src="/files/next.png" /></a>
<?php } // Show if not last page ?></li>
</ul>