Pagination Producing Unexpected Results. What did I do wrong? - php

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

Related

php pagination of an array with previous and next tab

I have this array which contain around 1000 records. I want to display 20 array records per page.
$list=array(
array([title]=>"sony", [description]=>"camera"),
array([title]=>"sony", [description]=>"mobiles"),
array([title]=>"lenovo", [description]=>"laptop"),
array([title]=>"lenovo", [description]=>"mobiles")
);
I have used the following code for pagination. It is giving me a long row for pagination. Can someone help me to include previous and next code to my existing code so that my pagination will look good.
$page = isset($_REQUEST['page']) && $_REQUEST['page'] > 0 ? $_REQUEST['page'] : 1;
function display($list, $page = 1)
{
$start = ($page - 1) * 2;
$list = array_slice($list, $start, 15);
foreach ($list as $key => $val) {
echo $val['title'] . '<br/>';
echo $val['description'] . '<br/>';
echo "<br>";
}} $len = count($list);
$pages = ceil($len / 2);
if ($page > $pages or $page < 1)
{
echo 'page not found';
}
else
{
display($list, $page);
for ($i = 1 ; $i <= $pages ; $i++)
{
$current = ($i == $page) ? TRUE : FALSE;
if ($current) {
echo '<b>' . $i . '</b>';
}
else
{
?>
<?php echo $i;?>
<?php
}
}
}
Here's an example with the data array from your question.
The example
The page size is assumed to be 2 (20 in your question).
The size of the data array does not matter.
The start parameter is provided (as in your example) thru a GET parameter http://localhost/flipkart-api/fkt_offer.php?…start=index_or_page. This parameter is available in the script as $_GET['start'].
The previous and next start indices are to be calculated ($start +/- $maxpage, etc.).
To keep this example simple, I took the start index, not the page number, as parameter. But you also could use a page number and calculate the index, of course.
For the reason of brevity I omitted error checking ("what if no more items", etc.).
Code:
<?php
// The data array
$list=array(
array('title'=>"sony", 'description'=>"camera"),
array('title'=>"sony", 'description'=>"mobiles"),
array('title'=>"lenovo", 'description'=>"laptop"),
array('title'=>"lenovo", 'description'=>"mobiles")
);
// Evaluate URL
$proto = ((isset($_SERVER["HTTPS"])) && (strtoupper($_SERVER["HTTPS"]) == 'ON')) ? "https://" : "http://";
$hname = getenv("SERVER_NAME");
$port = getenv("SERVER_PORT");
if ( (($port==80)&&($proto=='http://')) || (($port==443)&&($proto=='https://')) ) { $port = ''; }
$params = '';
foreach ($_GET as $key=>$value) {
if (strtolower($key)=='start') continue;
$params .= (empty($params)) ? "$key=$value" : "&$key=$value";
}
$url = $proto . $hname . $port. $_SERVER['SCRIPT_NAME'] . '?' . $params;
// Page contents
$last = count($list)-1;
$start = (isset($_GET['start'])) ? intval($_GET['start']) : 0;
if ($start<0) $start = 0; if ($start > $last) $start = $last;
$maxpage = 2;
echo "<p>Start index = $start</p>" . PHP_EOL;
$curpage = 0;
for($xi=$start; $xi<=$last; $xi++) {
if ($curpage >= $maxpage) break;
$curpage++;
echo 'Entry ' . $curpage .
': ' . $list[$xi]['title'] .
' - ' . $list[$xi]['description'] .
'<br />' . PHP_EOL;
}
// Navigation
$prev = $start - $maxpage; if ($prev<0) $prev = 0;
$next = ( ($start+$maxpage) > $last) ? $start : $start + $maxpage;
$prev = ( ($start-$maxpage) < 0) ? 0 : $start - $maxpage;
echo '<p>Previous ';
echo 'Next</p>';
?>
Result (e.g)
Start index = 2
Entry 1: lenovo - laptop
Entry 2: lenovo - mobiles
Previous Next

pagination with hash and parameters doesn't work

I have page with a URL like this:
http://***.com/profile/username#profile_favs
With my pagination it looks like this:
http://***.com/profile/username?s=0&p=1#profile_favs
The last example doesn't work.
Basically my pagination-function looks like this:
function Pagination($pages, $start, $display, $link_url="", $anchor="") {
echo '<div id="pagination">';
$current_page = ($start / $display) + 1;
$paginator_num = 5;
$pages_display = 10;
if ($current_page > $pages - $paginator_num) {
$paginator_num = $pages_display - ($pages - $current_page);
} elseif ($current_page < $paginator_num + 1) {
$paginator_num = $pages_display - $current_page;
} else {
$paginator_num = 5;
}
$min = max($current_page - $paginator_num, 1);
$max = min($current_page + $paginator_num, $pages);
for ($i = $min; $i <= $max; $i++) {
if ($i != $current_page) {
echo '<div class="pagination_link">';
echo '' . $i . '';
echo '</div>';
} else {
echo '<div id="pagination_active" class="pagination_link">';
echo $i . ' ';
echo '</div>';
}
}
echo '</div>';
}
And this is the part that calculates the pages (this part gets included right before my pagination-function):
<?php
$display = $display_num;
if (isset($_GET['p']) && is_numeric ($_GET['p'])) {
$pages = $_GET['p'];
} else {
$total_results = $qr_num;
if ($total_results > $display) {
$pages = ceil ($total_results / $display);
} else {
$pages = 1;
}
}
if (isset($_GET['s']) && is_numeric ($_GET['s'])) {
$start = $_GET['s'];
} else {
$start = 0;
}
?>
Now my question is: Is there any workaround possible to get that pagination working with a URL mentioned above:
http://***.com/profile/username?s=0&p=1#profile_favs
Actually I'd prefer a solution without GET-parameters.
You could use an AJAX call with the XMPHttpRequest Object to fetch it without the get parameters.
Another thing you could do (if you are using Apache) is to look at mod_rewrite for urls.
Hope that helps :)

Adding previous(back) and next buttons next to the page numbers PHP

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

How To Split A Line From An Array Into Two Variables Using PHP

Here is the script as I am using it now:
<?php
echo '<html><body>';
// Data from a flat file
$dataArray = file('text.dat');
// Get the current page
if (isset($_REQUEST['page'])) {
$currentPage = $_REQUEST['page'];
} else {
$currentPage = 'some default value';
}
// Pagination settings
$perPage = 3;
$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 $key => $val)
{
if($key >= $start && $key < $end)
$pagedData[] = $dataArray[$key];
}
foreach($pagedData AS $item)
echo ''. $item .'<br>';
if($currentPage > 0 && $currentPage < $numPages)
echo '« Previous page<br>';
if($numPages > $currentPage && ($currentPage + 1) < $numPages)
echo 'Next page »<br>';
echo '</body></html>';
?>
And here is the contents of text.dat
Fun
Games
Toys
Sports
Fishing
Pools
Boats
Now, my question is, What if text.dat looked like this?:
Fun||http://site.com/page11.html
Games||http://site.com/page12.html
Toys||http://site.com/page13.html
Sports||http://site.com/page16.html
Fishing||http://site.com/page18.html
Pools||http://site.com/page41.html
Boats||http://site.com/page91.html
I would like to know what to change in the script so I can basically do this instead:
foreach($pagedData AS $item1 and $item2)
echo ''. $item1 .'<br>';
Try:
foreach($pagedData AS $item) {
$item = explode('||', $item);
echo ''. $item[0] .'<br>';
}

php page navigation by serial number

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.

Categories