I am building a website and I want to add "previous" & "next" buttons to send the user to the previous or the next page. So i tried this:
where 'pid' is the 'post id' I did the same thing for 'next page' button
it worked... but it continues even if the page with that ID doesnt exist. im wondering if I could get some help with 'checking if current page is first row or last row.'.
Here's my code:
<?php
require('connect.php');
if(preg_match('/[^0-9]/i', $_REQUEST['pid'])) {
echo '<div style="margin:50px auto;" class="warning_msg">WARNING: !! Illegal character detected !! >> <b>'.$_REQUEST['pid'].'</b></div>';
} else {
$post_ = $dbh->query('SELECT * FROM `posts` WHERE `id`='.$dbh->quote($_REQUEST['pid']).'')->fetch();
echo '<div class="_header_ p_header_ disable_padding">
'.$post_['title'].'
<a href="?p=posts&pid='.($_REQUEST['pid']+1).'" class="next_page fa fa-hand-o-right" title="Next Post" ></a>
</div>
<div>'.$post_['article'].'</div>
<div class="_footer_">posted by <i>'.$post_['author'].'</i> on » '.date('M d Y H:m:i', strtotime($post_['post_time'])).'</div>';
}
?>
EDIT (SOLVED):
to find the first & last row i used a single query
$page = $dbh->query('SELECT MIN(id), MAX(id) FROM `posts`')->fetch();
and used like :
/* if current post id is equals to last id from posts */
if($_REQUEST['pid'] == $page[1]) { $next_page = $_REQUEST['pid'].'#';}
else { $next_page = ($_REQUEST['pid']+1); }
/* if current post id is equals to first id from posts */
if($_REQUEST['pid'] == $page[0]) { $prev_page = $_REQUEST['pid'].'#';}
else { $prev_page = ($_REQUEST['pid']-1); }
<?php
$lastpage = 10;
$ppage = isset($_REQUEST['pid']) && $_REQUEST['pid'] > 1 ? ($_REQUEST['pid']-1) : 0;
$npage = isset($_REQUEST['pid']) && $_REQUEST['pid'] < $lastpage ? ($_REQUEST['pid']+1) : $lastpage;
?>
Here i put a constant value 10 for last page.Instead of that you have to find outlast page id and replace that.Php pagination scripts are also available to find out first and last pages..
Related
I've set up a search of my database with pages. There are two searches performed on this page, one for users and one for pets, but for now I am trying to get it to work with the pet search only. The search itself functions, and the results display properly for page 1 with the appropriate amount of linked pages after. My problem comes in when I try to go beyond the first page. I have checked the search itself and it brings up results in my database, but clicking the page link results in a 'No results' message. Here is my initial setup:
<?php
if (!isset ($_GET['page']) ) {
$page = 1;
} else {
$page = $_GET['page'];
}
$results_per_page = 10;
$page_first_result = ($page-1) * $results_per_page;
$num_results = 0;
include("includes/header.php"); // This is where the first search is performed to check for number of rows
if (!empty($pet_search_result)) {
$number_of_result = mysqli_num_rows($pet_search_result);
$num_results = mysqli_num_rows($pet_search_result);
}
else if (!empty($user_search_result)) {
$number_of_result = mysqli_num_rows($user_search_result);
}
else {
$number_of_result = 0;
}
$number_of_page = ceil ($num_results / $results_per_page);
?>
This is of course followed by the search where users enter parameters. This search works perfectly without pagination. After those have been entered, the code says this:
$queryConditions = $queryConditions . ' LIMIT ' . $results_per_page . ' OFFSET ' . $page_first_result;
$pet_search_result2 = mysqli_query($con, "SELECT * from pets WHERE $queryConditions");
Results are then displayed, and here is where the problem hits.
for($page = 1; $page<= $number_of_page; $page++) {
echo " <a style ='color: white;' href='?page=$page'> $page </a> | ";
}
Clicking the link to page 2 or any other page leaves the user on the search page with no results shown. I have checked and the proper page number is picked up on page 2, the offset is correct, and the search itself turns up the appropriate results when performed directly in the database.
I have tried using
htmlentities($_SERVER['PHP_SELF'])
and
$_SERVER['PHP_SELF']
so that it read:
echo " <a href='" . htmlentities($_SERVER['PHP_SELF']) . "?page=$page'> $page </a> | ";
or
echo " <a style ='color: white;' href='" . $_SERVER['PHP_SELF'] . "?page=$page'> $page </a> | ";
as the redirect url, and none of these worked. I was expecting clicking page 2 to show me the search page with the second set of 10 results. Instead it acts as if no search has been performed.
Pagination PHP code:
<?php
//Connecting To The DB And Fetching Number Of Rows.
$stmt = $pdo->prepare('SELECT * FROM locations');
$stmt->execute();
$count = $stmt->rowCount();
$values = $stmt->fetchAll();
//Check If Page Number Is Set To Specific Value.
if (isset($_GET['pageno']))
{
$pageno = $_GET['pageno']; //Current Page Number.
$no_of_records_per_page = 100; // Number Of Rows Per Page.
$total_pages = ceil($count / $no_of_records_per_page); //Total Number Of Pages.
$offset = ($pageno-1) * $no_of_records_per_page; //Starting From.
}
//If Page Number Not Specified The First Page Will Be Shown.
else
{
$pageno = 1;
}
?>
HTML code beneath it:
<ul class="pagination">
//First Page.
<li>
First
</li>
//Previous Page.
<li>
Prev
</li>
<li>
//Loop Through Pages.
<?php
for ($i=1; $i <= $total_pages ; $i++)
{
echo ''.$i.'';
}
?>
</li>
//Next Page.
<li>
Next
</li>
//Last Page.
<li>
Last
</li>
It's showing all the pages:
First Previous 1 2 3 4 5 6 7 8 Next Last
But if there are many pages it would be missed up.
I want to show specific number of pages like 5 or 6:
First Previous 1 2 3 4 5 .. .. 8 Next Last
Is it possible ? Is there is a library / plugin for that?
Best use Data tables which will process the data server side, which will be your ajax call and data will load on click on next or on pagination. it will reduce the load of getting data at one go and you do not have to write separate code for the pagination too.
Refer below link.
https://datatables.net/examples/data_sources/server_side.html
Hope it will help you.
Depending on what you want displayed for the "extra" page number, change what is echoed in the if statement:
//Loop Through Pages.
<?php
for ($i=1; $i <= $total_pages ; $i++)
{
if($total_pages > 8 && $i > 6 && $i < $total_pages) {
echo '..';
} else {
echo ''.$i.'';
}
}
?>
I am trying to make pagination from one post to the next post in a single blog post. The problem is that when I open an article with ID-1 and I click on the 'next' button I get a blank/empty page.
This is the post page, which gets the ID of the chosen post in blog.php. This is what I have so far. Any suggestions?
<?php
// include database connection
require_once 'database.inc.php';
$pdo = Database::connect();
if(isset($_GET['post_id']) && is_numeric($_GET['post_id'])){
$post_id = $_GET['post_id'];
// page is the current page, if there's nothing set, default is page 1
$page = isset($_GET['page']) ? $_GET['page'] : 1;
// set records or rows of data per page
$recordsPerPage = 1;
// calculate for the query LIMIT clause
$fromRecordNum = ($recordsPerPage * $page) - $recordsPerPage;
// select all data
$query = "SELECT * FROM posts WHERE post_id = $post_id LIMIT {$fromRecordNum}, {$recordsPerPage}";
$stmt = $pdo->prepare( $query );
$stmt->execute();
//this is how to get number of rows returned
$num = $stmt->rowCount();
//check if more than 0 record found
if($num>0){
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo '
// post body ';
}
}
// *************** <PAGING_SECTION> ***************
// ***** for 'first' and 'previous' pages
if($page>1){
// ********** show the previous page
$prev_page = $page - 1;
echo "
<a href='" . $_SERVER['PHP_SELF'] . "?page={$prev_page}'>
<div class='prev-btn control-nav text-left'>
<h5>Previous Post</h5>
</div>
</a>";
}
// find out total pages
$query = "SELECT COUNT(*) as total_rows FROM posts";
$stmt = $pdo->prepare( $query );
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$total_rows = $row['total_rows'];
$total_pages = ceil($total_rows / $recordsPerPage);
if($page<$total_pages){
// ********** show the next page
$next_page = $page + 1;
echo "<a href='" . $_SERVER['PHP_SELF'] . "?page={$next_page}'>
<div class='next-btn control-nav text-right'>
<h5>Next Post</h5>
</div>
</a>";
}
}
?>
It's not very clear from your question, but I think your problem is this, your code requires the post_id parameter to be set:
if(isset($_GET['post_id']) && is_numeric($_GET['post_id'])){
$post_id = $_GET['post_id'];
}
But in your next and prev page links, you're not setting a post_id parameter:
echo "<a href='" . $_SERVER['PHP_SELF'] . "?page={$next_page}'>
<div class='next-btn control-nav text-right'>
<h5>Next Post</h5>
</div>
</a>";
Your code is inherently relying on a single post being shown, as determined by the post_id. Here's what I suggest, change:
// select all data
$query = "SELECT * FROM posts WHERE post_id = $post_id LIMIT {$fromRecordNum}, {$recordsPerPage}";
to:
// select all data
$query = "SELECT * FROM posts LIMIT {$fromRecordNum}, {$recordsPerPage}";
of course, then, you won't be able to show a specific post, but then again it's hard to know what you're actually trying to achieve here.
Could you show it in a working website? It would be easier to tell what is wrong then, but from the code it looks like you are making the url wrong in your anchor href part.
$prev_page = $post_id - 1;
<a href='" . $_SERVER['PHP_SELF'] . "?post_id={$prev_page}'>
<div class='prev-btn control-nav text-left'>
<h5>Previous Post</h5>
</div>
</a>"
$next_page = $post_id + 1;
and the link is there made in same manner as previous one
as i am not sure what your server php self is returning and you shouldnt be adding the second ? symbol in it, if it already had it and u should use & i think for get parameters as ? is only used once after the script file name once. Or you are either missing the ID in your url.
Also blank/empty page might be crashing the script on that page and if u have errors turned off you wont see it in webpage and will have to go to your php errors log file to look for them
EDIT: as block quote wasnt showing correctly.
It is because first you get $post_id but then in the links you put $page which doesn't contain your ID. Try to change your nex&prev links like this:
<a href='" . $_SERVER['PHP_SELF'] . "?post_id=".$prev_page."'>
<a href='" . $_SERVER['PHP_SELF'] . "?post_id=".$next_page."'>
Also don't forget to change the line for $page here:
$page = isset($_GET['page']) ? $_GET['page'] : 1;
to this
$page = isset($_GET['post_id']) ? $_GET['post_id'] : 1;
This should do the trick.
I have a mysql database and use a multi variable search page, find.php, to input variables. The results come out correctly (count is correct and so is page 1 of the results) but when I try and go to the next page I get an error :: Undefined index: term1 line 60 ::Undefined index: term2 line 61 and so on.
Search2.php is as set below:
<?php
include "db.inc.php";
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * 15;
$term1 = $_POST['term1'];
$term2 = $_POST['term2'];
$term3 = $_POST['term3'];
$term4 = $_POST['term4'];
$sql ="SELECT * FROM cdrequests WHERE pname LIKE '%$term1%' AND date LIKE '%$term2%' AND date LIKE '%$term3%' AND dept LIKE '%$term4%' LIMIT $start_from, 15";
$rs_result = mysql_query ($sql);
$num_rows = mysql_num_rows($rs_result);
$query = mysql_query("SELECT * FROM cdrequests WHERE pname LIKE '%$term1%' AND date LIKE '%$term2%' AND date LIKE '%$term3%' AND dept LIKE '%$term4%'");
$number=mysql_num_rows($query);
print "<font size=\"5\" color=white><b>CD Requests</b></font> </P>";
?>
pagination structure
<?php
$sql = "SELECT COUNT(id) FROM cdrequests WHERE pname LIKE '%$term1%' AND date LIKE '%$term2%' AND date LIKE '%$term3%' AND dept LIKE '%$term4%'";
$rs_result = mysql_query($sql);
$row = mysql_fetch_row($rs_result);
$total_records = $row[0];
$total_pages = ceil($total_records / 15);
/****** build the pagination links ******/
// range of num links to show
$range = 3;
// if not on page 1, don't show back links
if ($page > 1) {
// show << link to go back to page 1
echo " <a href='search2.php?page=1'><b>First</b></a> ";
// get previous page num
$prev = $page - 1;
// show < link to go back to 1 page
echo " <a href='search2.php?page=$prev'><b>«</b></a> ";
} // end if
// loop to show links to range of pages around current page
for ($x = ($page - $range); $x < (($page + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $total_pages)) {
// if we're on current page...
if ($x == $page) {
// 'highlight' it but don't make a link
echo " <font size='5' color=yellow><b> $x </b></font> ";
// if not current page...
} else {
// make it a link
echo " <a href='search2.php?page=$x'>$x</a> ";
} // end else
} // end if
} // end for
// if not on last page, show forward and last page links
if ($page != $total_pages) {
// get next page
$next = $page + 1;
// echo forward link for next page
echo " <a href='search2.php?page=$next'><b>»</b></a> ";
// echo forward link for lastpage
echo " <a href='search2.php?page=$total_pages'><b>Last</b></a> ";
} // end if
/****** end build pagination links ******/
echo '</table>';
?>
Somehow going to page 2 fails to carry over proper info of variable term 1, term2 etc.
Any idea/help appreciated
Your page links do not pass term1, term2, etc. back to the server. Also if you are going to pass them in the link then you need to check $_REQUEST['term1'], $_REQUEST['term2'], etc. to cover both GET and POST requests.
The code of the links should be like this:
echo " <a href='search2.php?page=$next".
"&term1=".urlencode($term1).
"&term2=".urlencode($term2).
"&term3=".urlencode($term3).
"&term4=".urlencode($term4)"'><b>»</b></a> ";
If you have too many parameters to pass to the server then you should probably consider sending POST requests when clicking on the links using JavaScript.
I've been building a website in PHP using a local install of MAMP on a MacBook Pro. Yesterday I finally managed to finish it with everything working so I decided to buy some webspace and host the files using exactly the same setup as the local install on MAMP (PHP 5.3, MySQL).
When I moved the files over and tested the site I get a really strange error. Most of the code is working, however, there are parts of the code that are broken, but in a very unusual way. I'll try my best to explain..
Note: This image probably shows off the error very well. I've blocked out some of the private content.
Image of the error
The first bit of code is this:
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
$sql = "SELECT * FROM message,thumbsup_items WHERE message.id = thumbsup_items.name AND message.date BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW() ORDER BY votes_down DESC LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
$dest = "http://twitter-badges.s3.amazonaws.com/t_mini-b.png";
$dest2 = "images/fb-small.png";
$url="http://dfwm.ws";
while ($row = mysql_fetch_assoc($result))
{
?>
Which is 100% working on the local install, however on the hosted website it cuts off at:
$totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
$sql = "SELECT * FROM message,thumbsup_items WHERE message.id = thumbsup_items.name AND message.date BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW() ORDER BY votes_down DESC LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
$dest = "http://twitter-badges.s3.amazonaws.com/t_mini-b.png";
$dest2 = "images/fb-small.png";
$url="http://dfwm.ws";
while ($row = mysql_fetch_assoc($result))
{
?>
Meaning that the error must be to do with the < operator?. I'm unsure.
The next error is below:
<?
/****** build the pagination links ******/
// if not on page 1, don't show back links
if ($currentpage > 1) {
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
?>
<div id = "previous">
<?
echo " <a href='?currentpage=$prevpage'>«Previous</a> ";?>
</div>
<?
} // end if
// range of num links to show
$range = 2;
?>
<div id="pagination">
<?
// 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 > 0) && ($x <= $totalpages)) {
// if we're on current page...
if ($x == $currentpage) {
// 'highlight' it but don't make a link
echo "$x";
// if not current page...
} else {
// make it a link
echo " <a href='?currentpage=$x'>$x</a> ";
} // end else
} // end if
} // end for
// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
?>
</div>
<?
// echo forward link for next page
?><div id ="next"><?
echo " <a href='?currentpage=$nextpage'>Next »</a> ";?>
Which cuts off at:
1) {
I've come to the conclusion that if it was an error to do with the operators, as it has happened on both times, surely it would just not show anything, instead of coming out of the PHP tag and just displaying it as HTML? (the image shows this at the start of the question).
Would really appreciate some help as I've been racking my brain over it for hours.
Thanks
<? is the short open tag, which only works on PHP installs with the setting to enable them. I suggest you use the full <?php.
You're using short tags (<? instead of the full <?php opening declaration) which are advised against for exactly this reason: incompatibility with some servers.
Re-write any instances of <? to <?php and make sure you use <?php in the future.