Can anyone help in this php page navigation script switch on counting normal serial number? In this script there is a var called "page_id" - I want this var to store the real page link by order like 0, 1, 2, 3, 4, 5 ...
<?
$onpage = 10; // on page
/*
$pagerecord - display records per page
$activepage - current page
$records - total records
$rad - display links near current page (2 left + 2 right + current page = total 5)
*/
function navigation($pagerecord, $activepage){
$records = 55;
$rad = 4;
if($records<=$pagerecord) return;
$imax = (int)($records/$pagerecord);
if ($records%$pagerecord>0)$imax=$imax+1;
if($activepage == ''){
$for_start=$imax;
$activepage = $imax-1;
}
$next = $activepage - 1; if ($next<0){$next=0;}
$end =0;
$prev = $activepage + 1; if ($prev>=$imax){$prev=$imax-1;}
$start= $imax;
if($activepage >= 0){
$for_start = $activepage + $rad + 1;
if($for_start<$rad*2+1)$for_start = $rad*2+1;
if($for_start>=$imax){ $for_start=$imax; }
}
if($activepage < $imax-1){
$str .= ' <<< End <span style="color:#CCCCCC">•</span> < Forward | ';
}
$meter = $rad*2+1; //$rad; ---------------------
for($i=$for_start-1; $i>-1; $i--){
$meter--;
//$line = '|'; if ($meter=='0'){ $line = ''; }
$line = ''; if ($i>0)$line = '|';
if($i<>$activepage){
$str .= " <a href='?page=".$i."&page_id=xxx'>".($i)."</a> ".$line." ";
} else {
$str .= " <strong>[".($i)."]</strong> ".$line." ";
}
if($meter=='0'){ break; }
}
if($activepage > 0){
$str .= " | <a href='?page=".$next."'>Back ></a> <span style='color:#CCCCCC'>•</span> <a href='?page=".($end)."'>Start >>></a> ";
}
return $str;
}
if(is_numeric($_GET["page"])) $page = $_GET["page"];
$navigation = navigation($onpage, $page); // detect navigation
echo $navigation;
?>
Instead xxx here (page_id=xxx) I want to link to real page number by normal order when this script show links but reversed.
Really need help with this stuff! Thanks in advance!
I were helped by one of the programmers with my above script. So here is a worked example of the reversed page navigation on PHP.
<?
$onpage = 10; // on page
/*
$pagerecord - display records per page
$activepage - current page
$records - total records
$rad - display links near current page (2 left + 2 right + current page = total 5)
*/
function navigation($pagerecord, $activepage){
$records = 126;
$rad = 4;
if($records<=$pagerecord) return;
$imax = (int)($records/$pagerecord);
if ($records%$pagerecord>0)$imax=$imax+1;
if($activepage == ''){
$for_start=$imax;
$activepage = $imax-1;
}
$next = $activepage - 1; if ($next<0){$next=0;}
$end =0;
$prev = $activepage + 1; if ($prev>=$imax){$prev=$imax-1;}
$start= $imax;
if($activepage >= 0){
$for_start = $activepage + $rad + 1;
if($for_start<$rad*2+1)$for_start = $rad*2+1;
if($for_start>=$imax){ $for_start=$imax; }
}
$meter = $rad*2+1; //$rad; ---------------------
$new_meter = $for_start-1;
if($activepage < $imax-1){
$str .= ' <<< End <span style="color:#CCCCCC">•</span> < Forward | ';
}
for($i=$for_start-1; $i>-1; $i--){
$meter--;
//$new_meter++;
//$line = '|'; if ($meter=='0'){ $line = ''; }
$line = ''; if ($i>0)$line = '|';
if($i<>$activepage){
$str .= " <a href='?page=".$i."&page_id=".($imax-$i-1)."'>".($i)."</a> ".$line." ";
} else {
$str .= " <strong>[".($i)."]</strong> ".$line." ";
}
if($meter=='0'){ break; }
}
if($activepage > 0){
$str .= " | <a href='?page=".$next."&page_id=".($imax-$next-1)."'>Back ></a> <span style='color:#CCCCCC'>•</span> <a href='?page=".($end)."&page_id=".($start-1)."'>Start >>></a> ";
}
return $str;
}
if(is_numeric($_GET["page"])) $page = $_GET["page"];
$navigation = navigation($onpage, $page); // detect navigation
echo $navigation;
?>
$page = keeps the page number from the reversed order
$page_id = keeps the real page by serial order. so you can make SELECT queries to database and ORDER BY id DESC use.
Related
i create a php news system, but i have a problem:
<?php
include('config.php');
if( isset( $_GET["page"]) ) $PAGE=$_GET["page"]; else $PAGE=1;
$query1=mysql_query("select id, name, email , age from addd LIMIT ". (($PAGE * 5) - 5) .",5");
echo "<table><tr><td>Testo</td><td>Nome</td><td>Anni</td></tr>";
function truncate_string($str, $length) {
if (!(strlen($query2['name']) <= $length)) {
$query2['name'] = substr($query2['name'], 0, strpos($query2['name'], ' ', $length)) . '...';
}
return $query2['name'];
}
while($query2=mysql_fetch_array($query1))
{
$number= $query2['name'];
echo "<tr><td>".substr($query2['name'], 0, 500)."...</td>";
echo "<td>".$query2['email']."</td>";
echo "<td>".$query2['age']."</td>";
echo "<td>".str_word_count($number)."</td>";
echo "<td><a href='edit.php?id=".$query2['id']."'>Mod</a></td>";
echo "<td><a href='delete.php?id=".$query2['id']."' onclick=\"return confirm('Sei sicuro di volerlo eliminare?');\");'>Canc</a></td><tr>";
echo "<td><a href='singletwo.php?id=".$query2['id']."');'>vedi</a></td<tr>";
}
?>
The pages follow this numbering: ?page=1, ?page=2 ecc.
Each page contains 5 news.
How do I create an automatic pagination system?
With Prev-Next, automatically detect possible next or previous pages?
I don't know how to do it.
Start by having the max length and total number of rows in variables:
<?php
include('config.php');
$max = 5;
$total = mysql_query("select count(*) from addd");
$PAGE = isset($_GET["page"]) ? $_GET["page"] : 1;
$query1 = mysql_query("select id, name, email , age from addd LIMIT " . (($PAGE * $max) - $max) . "," . $max);
That way, you can calculate how many pages you'll need.
The following code will give you a page list (Page 1, Page 2, Page 3 etc.):
for($i = 0; $i < ceil($total / $max); $i ++)
{
$p = $i + 1;
echo 'Page ' . $p . '';
}
If you'd rather have Previous and Next links, try this:
if($PAGE > 1)
echo '<a href="?page=' . ($PAGE - 1) . '>Previous</a>';
if(ceil($total / $max) > $PAGE)
echo '<a href="?page=' . ($PAGE + 1) . '>Next</a>';
What you could do is:
$currentPage = isset($_GET['page']) ? $_GET['page'] : 1;
$limit = $currentPage*5;
$offset = $offset-5;
Now that you have these numbers, you can use them in your query:
$stmt = "SELECT
...
FROM news
LIMIT ".$offset.", ".$limit.";
This way you'll get the records you want. As far as the next and previous buttons go:
if ($currentPage > 1) {
// Show previous button
}
For the next button you'll need to do another query:
$stmt = "SELECT COUNT(*) as total FROM news";
$result = $pdo->fetch();
$totalRows = $result['total'];
if ($currentPage < round($totalRows/5)) {
// Show next button
}
I was able to create a working pagination system for my application. But the problem I am having is when a user does a search, it can/will display over 100 pages in the pagination.
I am trying to figure out how to show only like 5 on each side of the current page. I would like to create a FIRST page button, and a LAST page button, but I'll deal with that later.
So here is the first part of code that counts the records in the database table:
<?php
function countRecords()
{
// The application takes a lot of user input, which then builds a query here.
// The user input goes into a session variable called $_SESSION['where']
// I'll start with the actual query code
$sql = "SELECT COUNT(DISTINCT CONTAINER_NUMBER) AS TOTAL
FROM 'contTable'" . " WHERE (" . $_SESSION['where'] . ");";
$sqlres = #mysql_query($sql) or die();
$row = mysql_fetch_row($sqlres);
$return $row[0];
}
So code above gets the count from the table depending on the search criteria.
Here is the next piece of code that prints the grid. I'll keep it as short as possible:
function displayrecords()
{
$rec_limit = 100;
$targetpage = "containers.php";
if(isset($_GET['page']))
{
$page = $_GET['page'];
$offset = $rec_limit * ($page - 1);
}
else
{
$page = 1;
$offset = $rec_limit * ($page - 1);
}
$left_rec = countRecords() - ($page * $rec_limit);
$select = "";
$_SESSION['where'] = "";
// user input variables are here that build a variable called $_SESSION['where']
// I'll skip the code down to the query
if ($_SESSION['where'] != "") $select = "SELECT * FROM 'contTable'" . " WHERE
(" . $_SESSION['where'] . ") GROUP BY container, bol LIMIT " . $offset . ",
" . $rec_limit . ";";
}
Please excuse any typos or missing brackets and whatnot. Just know the above code works.
Now here is the code for the rest of the pagination:
$total_records = countRecords();
$total_pages = ceil($total_records / $rec_limit);
$adjacents = 5; // I just added this variable. I don't know what to do with it
$previousPage = $page - 1;
$nextPage = $page + 1;
$querystring = "";
foreach ($_GET as $key => $value)
{
if ($key != "page") $querystring .= "$key=$value&";
}
echo '<ul style="border: 0px solid red; margin: 3px;" class="pager">';
if ($left_rec < $rec_limit)
{
$last = $page - 2;
echo #"<li><a href=\"$targetpage?page=$previousPage&$querystring\">
Previous</a></li>";
for($i = 1; $i <= $total_pages; $i++)
{
echo #"<li " . ((($page+1)==$i)? "class=\"active\"" : "") . ">
$i</li>";
}
}
else if ($page == 0)
{
for($i = 1; $i <= $total_pages; $i++)
{
echo #"<li " . ((($page+1)==$i)? "class=\"active\"" : "") . ">
$i</li>";
}
echo #"<li>Next</li>";
}
else if ($page > 0)
{
$last = $page - 2;
echo #"<li><a href=\"$targetpage?page=$previousPage&$querystring\">
Previous</a></li> ";
for($i = 1; $i <= $total_pages; $i++)
{
echo #"<li " . ((($page+1)==$i)? "class=\"active\"" : "") . ">
$i</li>";
}
echo #"<li>Next</li>";
}
echo '</ul>';
}
So, with all of the code above, I can display a grid, and display the pages at the bottom of the application. But I don't want to show all 100 pages, only 5 on each side of the current page. I know I need to utilize the variable called $adjacents and plug it in to the paging portion of the code. But I'm not exactly sure how to do it.
I hope I am being clear on my request.
Please help.
Instead of looping through all of the pages:
for($i = 1; $i <= $total_pages; $i++)
Try doing something like this:
$start = ($page < $adjacents ? 1 : $page - $adjacents);
$end = ($page > $total_pages - $adjacents ? $total_pages : $page + $adjacents);
for($i= $start; $i <= $end; $i++)
//Here you can loop through the numbers within adjacents of the current page
I am using code A, and everything is as expected. When I try to add pagination script(code B), the results are no longer as expected. What did I do wrong? Any assistance would be much appreciated. Thanks....
code A:
$data = 'path/to/file.txt';
$counts = array_count_values(
array_map(function($line){return strtoupper(end(explode('||', $line, -4)));},
array_filter(file($data), 'trim')));
foreach($counts as $key1=>$value){
echo '<div>'. $key1 .' - '. $value .'</div>';
}
code B:
$link_range = 2;
$listings = 2;
if (isset($_SERVER['QUERY_STRING'])) {
$currentPage = $_SERVER['QUERY_STRING'];
} else {
$currentPage = '0';
}
$reg_ex = "[page=]";
$replace_word = "";
$str = $currentPage;
$currentPage = ''.ereg_replace($reg_ex, $replace_word, $str).'';
$data = 'path/to/file.txt';
$counts = array_count_values(
array_map(function($line){return strtoupper(end(explode('||', $line, -4)));},
array_filter(file($data), 'trim')));
$dataArray = $counts;
// Pagination settings
$perPage = $listings;
$numPages = ceil(count($dataArray) / $perPage);
if(!$currentPage || $currentPage > $numPages)
$currentPage = 0;
$start = $currentPage * $perPage;
$end = ($currentPage * $perPage) + $perPage;
// Extract ones we need
foreach($dataArray AS $keys => $val)
{
if($keys >= $start && $keys < $end)
$pagedData[] = $dataArray[$keys];
}
$range = $link_range;
if ($currentPage > 0 && $currentPage < $numPages) {
// show << link to go back to page 1
echo '<< |';
// get previous page num
$prevpage = $currentPage - 1;
// show < link to go back to 1 page
echo ' < |';
} // end if
// loop to show links to range of pages around current page
for ($x = ($currentPage - $range); $x < (($currentPage + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > -1) && ($x <= $numPages - 1)) {
// if we're on current page...
if ($x == $currentPage) {
// 'highlight' it but don't make a link
echo ' '. ($x + 1) .' |';
// if not current page...
} else {
// make it a link
echo ' '. ($x + 1) .' |';
} // end else
} // end if
} // end for
if ($currentPage != $numPages - 1) {
// get next page
$nextpage = $currentPage + 1;
// echo forward link for next page
echo ' > |';
// echo forward link for lastpage
echo ' >>
';
} // end if
foreach($pagedData as $key1=>$value){
echo '<div>'. $key1 .' - '. $value .'</div>';
}
Lets say file.txt contains:
a||b||Vietnam||c||d||e||f
a||b||HONG KONG||c||d||e||f
a||b||Vietnam||c||d||e||f
a||b||INDONESIA||c||d||e||f
a||b||UNITED STATES||c||d||e||f
ect.
Your problem is here (in which there's confusion about keys/values):
// Extract ones we need
foreach($dataArray AS $keys => $val)
{
if($keys >= $start && $keys < $end)
$pagedData[] = $dataArray[$keys];
}
Just replace that code with:
$pagedData = array_slice($dataArray, $start, $listings, true);
array_slice documentation
I have two tiny little problems;
1 . I want to add a previous / next button into this code
2 . I want it to only show like max 10 links between previous and next. So if i have 50 numbers/links it will only show 10 of them and not 50 links on the page.
I have searched on the clo
The code works, only need that two options in it.
Can someone help me out? Thank you !
<?php
include 'includes/connection.php';
$per_page = 8;
$pages_query = mysql_query("SELECT COUNT(`id`) FROM `products`");
$pages = ceil(mysql_result($pages_query, 0) / $per_page);
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $per_page;
$query = mysql_query("SELECT `name` FROM `products` LIMIT $start, $per_page");
while ($query_row = mysql_fetch_assoc($query)) {
echo '<p>', $query_row['name'] ,'</p>';
}
if ($pages >= 1 && $page <= $pages) {
for ($x=1; $x<=$pages; $x++) {
//echo $x, ' ';
echo ($x == $page) ? '<strong>'.$x.'</strong> ' : ''.$x.' ';
}
}else{
header("location:index.php?page=1");
}
?>
First of all, you should, just for good practice, put an "exit;" after the header() call at the end. It doesn't make a difference in this particular script, but keep in mind that any code following a header("Location: ...") call WILL be executed before redirection.
Now to your question, try this (UPDATE: This code has been tested and works.)
<?php
include 'includes/connection.php';
$per_page = 8;
$pages_query = mysql_query("SELECT COUNT(`id`) FROM `products`");
$pages = ceil(mysql_result($pages_query, 0) / $per_page);
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $per_page;
$query = mysql_query("SELECT `name` FROM `products` LIMIT $start, $per_page");
while ($query_row = mysql_fetch_assoc($query))
{
echo '<p>' . $query_row['name'] . '</p>';
}
// If the requested page is less than 1 or more than the total number of pages
// redirect to the first page
if($pages < 1 || $page > $pages)
{
header('Location: ?page=1');
// end execution of the rest of this script
// it will restart execution after redirection
exit;
}
// If more than one page, show pagination links
if($pages > 1)
{
$html = array();
$html[] = '<strong>';
// if you're on a page greater than 1, show a previous link
$html[] = (($page > 1) ? 'Previous ' : '');
// First page link
$pageFirst = '1';
$html[] = (($page == 1) ? "</strong>{$pageFirst}<strong>" : $pageFirst);
if ($pages > 6)
{
$start_cnt = min(max(1, $page - (6 - 1)), $pages - 6);
$end_cnt = max(min($pages, $page + 4), 8);
$html[] = ($start_cnt > 1) ? '...' : ' ';
for ($i = $start_cnt + 1; $i < $end_cnt; $i++)
{
$html[] = ($i == $page) ? '</strong>' . $i . '<strong>' : '' . $i . '';
if ($i < $end_cnt - 1)
{
$html[] = ' ';
}
}
$html []= ($end_cnt < $pages) ? '...' : ' ';
}
else
{
$html[] = ' ';
for ($i = 2; $i < $pages; $i++)
{
$html[] = ($i == $page) ? '</strong>' . $i . '<strong>' : '' . $i . '';
if ($i < $pages)
{
$html[] = ' ';
}
}
}
// last page link
$pageLast = '' . $pages . '';
$html[] = (($page == $pages) ? "</strong>{$pageLast}<strong>" : $pageLast);
// Show next page link if you're on a page less than the total number of pages
$html[] = ($page < $pages) ? ' Next' : '';
// If you're not on the last page, show a next link
$html[] = '</strong>';
}
else
{
// show page number 1, no link.
$html[] = '<strong>1</strong>';
}
echo implode('', $html);
Also note that the final ?> is not required in PHP files that do not have HTML code following the PHP code, so I left it off.
Buddy refer this URL
http://www.codediesel.com/php/simple-pagination-in-php/
OR
http://www.phpfreaks.com/tutorial/basic-pagination
Surely will help you.
Thanks
here is my paging code:
function getPagingQuery($sql, $itemPerPage = 10)
{
if (isset($_GET['page']) && (int)$_GET['page'] > 0) {
$page = (int)$_GET['page'];
} else {
$page = 1;
}
// start fetching from this row number
$offset = ($page - 1) * $itemPerPage;
return $sql . " LIMIT $offset, $itemPerPage";
}
function getPagingLink($sql, $itemPerPage = 10, $strGet ="")
{
$result = dbQuery($sql);
$pagingLink = '';
$totalResults = dbNumRows($result);
$totalPages = ceil($totalResults / $itemPerPage);
// how many link pages to show
$numLinks = 10;
// create the paging links only if we have more than one page of results
if ($totalPages > 1) {
$self = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] ;
if (isset($_GET['page']) && (int)$_GET['page'] > 0) {
$pageNumber = (int)$_GET['page'];
} else {
$pageNumber = 1;
}
// print 'previous' link only if we're not
// on page one
if ($pageNumber > 1) {
$page = $pageNumber - 1;
if ($page > 1) {
$prev = " [Prev] ";
} else {
$prev = " [Prev] ";
}
$first = " [First] ";
} else {
$prev = ''; // we're on page one, don't show 'previous' link
$first = ''; // nor 'first page' link
}
// print 'next' link only if we're not
// on the last page
if ($pageNumber < $totalPages) {
$page = $pageNumber + 1;
$next = " [Next] ";
$last = " [Last] ";
} else {
$next = ''; // we're on the last page, don't show 'next' link
$last = ''; // nor 'last page' link
}
$start = $pageNumber - ($pageNumber % $numLinks) + 1;
$end = $start + $numLinks - 1;
$end = min($totalPages, $end);
$pagingLink = array();
for($page = $start; $page <= $end; $page++) {
if ($page == $pageNumber) {
$pagingLink[] = " $page "; // no need to create a link to current page
} else {
if ($page == 1) {
$pagingLink[] = " $page ";
} else {
$pagingLink[] = " $page ";
}
}
}
$pagingLink = implode(' | ', $pagingLink);
// return the page navigation link
$pagingLink = $first . $prev . $pagingLink . $next . $last;
}
return $pagingLink;
}
im calling it like:
$sql = "something";
$result = mysql_query(getPagingQuery($sql, $rowsPerPage));
$pagingLink = getPagingLink($sql, $rowsPerPage, $url);
now if my url is like
http://xyz/abc/list.php its working fine.
but when my url is like
http://xyz/abc/list.php?action=def
after i click on page 2 the url changes like http://xyz/abc/list.php?page2&
'action=def' part is gone so the result changes.
if i use to pass the value in $strGet as $_SERVER['QUERY_STRING']
the 1st time it is ok like http://xyz/abc/list.php?page2&action=def
but from the 2nd time onwards it gives like http://xyz/abc/list.php?page3&page2&action=def
so not getting the desired result.
whereas i want it to be like http://xyz/abc/list.php?page3&action=def
plz help.. thanxx in advance
So I consider you use $_GET['page'] ^^
$_GET['page']=$page;
$url = 'http://xyz/abc/list.php?';
foreach($_GET as $key=>$param) {
$url.=$key.'='.$param.'&';
}
use http_build_query() instead of $_SERVER['QUERY_STRING']
What i would do is before setting $page = url code. i would first echo $page before and after setting it. so that i can see exactly what the values are. And i would print echo statements before and after everytime i set $page with the url to make sure it is correct. and if in any place you can see that its not the desired output because you can see that from the echo statements then you can make the right changes to make sure the $page variable is set properly.
what i would do then to set it properly is clear the $page variable and make sure that the $page variable is then set freshly with the url.
also when setting the url make sure that the $strGet variable is also echoed out first to make sure that it is the right value that you want to set. and then set the url to the $page variable.
By doing this simple debugging you are making sure all the values are correct first and you know it is before setting them.
give it a go
let me know what happens
PK