I have a small script that displays blog posts from a text file, how can I add pagination so that it only shows 5 blog posts at a time?
Here is the script:
<html>
<head>
<title>blog</title>
</head>
<body>
<?php
$mode = 0;
if ($mode == 0) { $opFile = "blogfile.txt"; }
$fp = fopen($opFile,"r") or die("Error Reading File");
$data = fread($fp, filesize($opFile));
fclose($fp);
$line = explode("\n", $data);
$i=count($line);
for ($n=0 ; $n < $i-1 ; $n++ ) {
$blog = explode("|", $line[$n]);
if (isset($blog[0]))
{
echo "<div class=\"blog-post\">";
echo "<p class=\"blog-title\">".$blog[1]."</p>";
echo "<p class=\"blog-message\">".$blog[2]."</p>";
echo "<p class=\"blog-date\">Posted: " .$blog[0]."</p>";
echo "<div style=\"clear: both;\"></div>";
echo "</div>";
}
}
?>
</body>
</html>
And here is the text file:
Feb 17 2010|Title|Blog post content here|[end]
Feb 17 2010|Title|Blog post content here|[end]
Feb 17 2010|Title|Blog post content here|[end]
Feb 17 2010|Title|Blog post content here|[end]
Any help is greatly appreciated!
Something like this:
<html>
<head>
<title>blog</title>
</head>
<body>
<?php
$POSTS_PER_PAGE = 10;
//Not sure what this is for, but I left it?
$mode = 0;
if ($mode == 0) { $opFile = "blogfile.txt"; }
//Explode the textfile into lines
$lines = file($opFile);
$posts = array();
foreach($lines as $line) {
//Ignore blank lines
if($line != "") {
//Explode each non-empty line
$post = explode("|", $line);
//Store the blog post
array_push($posts, $post)
}
}
//Output the pagination links
echo "<div class=\"blog-pagination\">";
for($i = 1; $i < ceil(count($posts) / $POSTS_PER_PAGE; $i++) {
echo '' + $i + ' ';
}
echo "</div>";
//Assume the user wants the first page if it's not specified
if(!isset($_GET['page'])) {
$_GET['page'] = 1;
}
//Figure out the first and last posts on this page
$first_post = ($_GET['page'] - 1) * $POSTS_PER_PAGE;
$last_post = $_GET['page'] * $POSTS_PER_PAGE - 1;
//Display the requested posts
for($i = $first_post; $i <= $last_post; $i++) {
echo "<div class=\"blog-post\">";
echo "<p class=\"blog-title\">".$blog[1]."</p>";
echo "<p class=\"blog-message\">".$blog[2]."</p>";
echo "<p class=\"blog-date\">Posted: " .$blog[0]."</p>";
echo "<div style=\"clear: both;\"></div>";
echo "</div>";
}
?>
(This is completely untested, but hopefully you can take it from here!)
This worked in my tests:
define('MAX_PER_PAGE',10);
// sanity checks for per-page and page index
$numPosts = ctype_digit((string)$_GET['perpage']) ? $_GET['perpage'] : 5;
$ostart = $start = max(1, ctype_digit((string)$_GET['page']) ? $_GET['page'] : 1) - 1;
$mode = 0;
if ($mode == 0) {
$file = "blogfile.txt";
}
// read the file into an array, strip newlines and ignore empty lines
file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES | FILE_TEXT);
// sort array (see custom function at bottom)
usort($line, 'blogsort');
$lines = count($line);
// get total number of pages
$numPages = ceil($lines / $numPosts);
// additional sanity checks (also sets $ostart if it was invalid; used later)
$numPosts = min(MAX_PER_PAGE, max(1, $numPosts));
if ($start * $numPosts > $lines ) {
$ostart = $start = max(0, $lines - $numPosts);
}
else {
$start *= $numPosts;
}
// Only grab the part of the array we need
$sliced = array_slice($line, $start, $numPosts);
// loop through posts, but break early if we run out
for ($n = 0; $n < $numPosts && isset($sliced[$n]); $n++ ) {
$blog = explode("|", $sliced[$n]);
if (isset($blog[0])) {
echo "<div class=\"blog-post\">\n",
"<p class=\"blog-title\">{$blog[1]}</p>\n",
"<p class=\"blog-message\">{$blog[2]}</p>\n",
"<p class=\"blog-date\">Posted: {$blog[0]}</p>\n",
"<div style=\"clear: both;\"></div>\n",
"</div>\n\n";
}
}
// back link
if ($ostart > 0) {
echo "← Older";
}
else {
echo "None Older";
}
echo " || ";
// forward link
if ($ostart + 1 < $numPages) {
$next = $ostart + 2;
echo "Newer →";
}
else {
echo "None Newer";
}
function blogsort($a, $b) {
$dateA = strtotime(substr($a, 0, strpos($a, '|')));
$dateB = strtotime(substr($b, 0, strpos($b, '|')));
if ($dateA == $dateB) {
return 0;
}
elseif ($dateA > $dateB) {
return -1;
}
else {
return 1;
}
}
Related
I have a small script that displays blog posts from a text file, how can I add pagination so that it only shows 5 blog posts at a time?
Here is the script:
<html>
<head>
<title>blog</title>
</head>
<body>
<?php
$mode = 0;
if ($mode == 0) { $opFile = "blogfile.txt"; }
$fp = fopen($opFile,"r") or die("Error Reading File");
$data = fread($fp, filesize($opFile));
fclose($fp);
$line = explode("\n", $data);
$i=count($line);
for ($n=0 ; $n < $i-1 ; $n++ ) {
$blog = explode("|", $line[$n]);
if (isset($blog[0]))
{
echo "<div class=\"blog-post\">";
echo "<p class=\"blog-title\">".$blog[1]."</p>";
echo "<p class=\"blog-message\">".$blog[2]."</p>";
echo "<p class=\"blog-date\">Posted: " .$blog[0]."</p>";
echo "<div style=\"clear: both;\"></div>";
echo "</div>";
}
}
?>
</body>
</html>
And here is the text file:
Feb 17 2010|Title|Blog post content here|[end]
Feb 17 2010|Title|Blog post content here|[end]
Feb 17 2010|Title|Blog post content here|[end]
Feb 17 2010|Title|Blog post content here|[end]
Any help is greatly appreciated!
Something like this:
<html>
<head>
<title>blog</title>
</head>
<body>
<?php
$POSTS_PER_PAGE = 10;
//Not sure what this is for, but I left it?
$mode = 0;
if ($mode == 0) { $opFile = "blogfile.txt"; }
//Explode the textfile into lines
$lines = file($opFile);
$posts = array();
foreach($lines as $line) {
//Ignore blank lines
if($line != "") {
//Explode each non-empty line
$post = explode("|", $line);
//Store the blog post
array_push($posts, $post)
}
}
//Output the pagination links
echo "<div class=\"blog-pagination\">";
for($i = 1; $i < ceil(count($posts) / $POSTS_PER_PAGE; $i++) {
echo '' + $i + ' ';
}
echo "</div>";
//Assume the user wants the first page if it's not specified
if(!isset($_GET['page'])) {
$_GET['page'] = 1;
}
//Figure out the first and last posts on this page
$first_post = ($_GET['page'] - 1) * $POSTS_PER_PAGE;
$last_post = $_GET['page'] * $POSTS_PER_PAGE - 1;
//Display the requested posts
for($i = $first_post; $i <= $last_post; $i++) {
echo "<div class=\"blog-post\">";
echo "<p class=\"blog-title\">".$blog[1]."</p>";
echo "<p class=\"blog-message\">".$blog[2]."</p>";
echo "<p class=\"blog-date\">Posted: " .$blog[0]."</p>";
echo "<div style=\"clear: both;\"></div>";
echo "</div>";
}
?>
(This is completely untested, but hopefully you can take it from here!)
This worked in my tests:
define('MAX_PER_PAGE',10);
// sanity checks for per-page and page index
$numPosts = ctype_digit((string)$_GET['perpage']) ? $_GET['perpage'] : 5;
$ostart = $start = max(1, ctype_digit((string)$_GET['page']) ? $_GET['page'] : 1) - 1;
$mode = 0;
if ($mode == 0) {
$file = "blogfile.txt";
}
// read the file into an array, strip newlines and ignore empty lines
file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES | FILE_TEXT);
// sort array (see custom function at bottom)
usort($line, 'blogsort');
$lines = count($line);
// get total number of pages
$numPages = ceil($lines / $numPosts);
// additional sanity checks (also sets $ostart if it was invalid; used later)
$numPosts = min(MAX_PER_PAGE, max(1, $numPosts));
if ($start * $numPosts > $lines ) {
$ostart = $start = max(0, $lines - $numPosts);
}
else {
$start *= $numPosts;
}
// Only grab the part of the array we need
$sliced = array_slice($line, $start, $numPosts);
// loop through posts, but break early if we run out
for ($n = 0; $n < $numPosts && isset($sliced[$n]); $n++ ) {
$blog = explode("|", $sliced[$n]);
if (isset($blog[0])) {
echo "<div class=\"blog-post\">\n",
"<p class=\"blog-title\">{$blog[1]}</p>\n",
"<p class=\"blog-message\">{$blog[2]}</p>\n",
"<p class=\"blog-date\">Posted: {$blog[0]}</p>\n",
"<div style=\"clear: both;\"></div>\n",
"</div>\n\n";
}
}
// back link
if ($ostart > 0) {
echo "← Older";
}
else {
echo "None Older";
}
echo " || ";
// forward link
if ($ostart + 1 < $numPages) {
$next = $ostart + 2;
echo "Newer →";
}
else {
echo "None Newer";
}
function blogsort($a, $b) {
$dateA = strtotime(substr($a, 0, strpos($a, '|')));
$dateB = strtotime(substr($b, 0, strpos($b, '|')));
if ($dateA == $dateB) {
return 0;
}
elseif ($dateA > $dateB) {
return -1;
}
else {
return 1;
}
}
I have the following code:
$max = 4;
$page = isset($_GET['page']) ? ($_GET['page']) : '1';
$init = $page - 1;
$init= $max * $init;
$strCount = "SELECT COUNT(*) AS 'total_mytable' FROM mytable";
$varstrCount = $crud->viewdatas($strCount);
$total = 0;
if(count($varstrCount)){
foreach ($varstrCount as $row) {
$total = $row["total_mytable"];
}
}
$result = "SELECT * FROM mytable ORDER BY id_mytable LIMIT $init,$max";
$varresult = $crud->viewdatas($result);
content of page:
<?php
if(count($varresult)){
foreach ($varresult as $res) {
?>
<h5><?php echo $res['title'] ?></h5>
<?php
}
}
?>
<?php
$max_links = 10;
$previous = $page - 1;
$next = $page + 1;
$pgs = ceil($total / $max);
if($pgs > 1 ){
if($previous > 0){
echo "<li><a href='".BASE_URL."/category/$previous' aria-label='Previous'><span aria-hidden='true'>«</span></a></li>";
} else{
}
for($i=$page-$max_links; $i <= $pgs-1; $i++) {
if ($i <= 0){
}else{
if($i != $page{
if($i == $pgs){ //if end insert 3 dots
echo "<li><a href='".BASE_URL."/category/".($i)."'>".$i."</a></li> ...";
}else{
echo "<li><a href='".BASE_URL."/category/".($i)."'>".$i."</a></li>";
}
} else{
if($i == $pgs){ //if end insert 3 dots
echo "<li>".$i."</li> ...";
}else{
echo "<li>".$i."</li>";
}
}
}
}
if($next <= $pgs){
echo "<li><a href='".BASE_URL."/category/$next' aria-label='Next'><span aria-hidden='true'>»</span></a></li>";
}else{
}
}
?>
The result:
And I not understand the reason for the active number stay right off the paging menu
In the code I defined max-links for 10, but no show number 5 and if I define max links for 3 changes nothing , displays the same result as the image.
Thanks for any help
echo "<li>".$i."</li>";
on the above line add up a href, seems like you have css formatting for li>a because of which you are not getting the required formatting on only li. so for getting better formatting for all paging links current, prev, next. you need to add up a tags.
echo "<li><a>".$i."</a></li>"; //in your else part
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 :)
I want to limit the number of pages displayed on my pagination php script below. This was a script made a few years back for me, and although I have read through similar problems on here, their coding is very different.
Any help with this would be really appreciated.
Here is my current script:
<?php
if ($max_pages>1) {
echo "<br>";
if ($page>0) {
echo 'Previous';
}
for ($x=0;$x<$max_pages;$x++) {
if ($page<>$x) {
echo ''.($x+1).'';
}
else {
echo '<span class="pagination">'.($x+1).'</span>';
}
}
if (($page+1<>$max_pages)) {
echo 'Next';
}
}?>
Your current script cycles $x between 0 and $max_pages.
What you can do is first replace them with $from_page and $to_page:
$from_page = 0;
$to_page = $max_pages;
...
for ($x=$from_page; $x < $to_page; $x++)
at which point the script will work just as before.
Now if you want to only display from $N pages before to $N pages after $page,
$N = 5; // display 5+5+1 = 11 pages
$from_page = $page - $N; if ($from_page < 0) $from_page = 0;
$to_page = $from_page + 2*$N+1; if ($to_page > $max_pages) $to_page = $max_pages;
$from_page = $to_page - 2*$N-1; if ($from_page < 0) $from_page = 0;
Not the most elegant way perhaps, but it will try to fit an 11-page area centered on the current page. You may want to also display a link to pages 0 and $max_pages-1.
MRE version
<?php
if ($max_pages>1)
{
$N = 5; // display 5+5+1 = 11 pages
$to_page = min($max_pages, max(0, $page - $N) + 2*$N+1);
$from_page = max($to_page - 2*$N-1, 0);
echo "<br>";
if ($page > 0)
{
echo 'Previous';
}
for ($x=$from_page; $x < $to_page; $x++) {
if ($page != $x) {
echo ''.($x+1).'';
}
else {
echo '<span class="pagination">'.($x+1).'</span>';
}
}
if (($page+1<>$max_pages)) {
echo 'Next';
}
}?>
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