Pagination with multiple GET values doesn't work as expected - php

I have the url to my blog page:
www.something.com/index.php?menuid=6 or just www.something.com/?menuid=6
I would like to add a GET variable (the page number, because there are too much posts to display them on one page) to the current url, like this:
www.something.com/index.php?id=6&page=12 or www.something.com/?id=6&page=12
What should i write in the <a href> of the pagination if I don't know the www.something.com and the value of the menuid?
I tried this:
$pagination = "<p>";
$pagination.= ($page <= 1) ? "First | " : "First | ";
$pagination.= ($page <= 1) ? "Previous | " : "Previous | ";
for ($i=1; $i<=$pages; $i++) {
$pagination.= ($page == $i) ? "{$i} | " : "{$i} | ";
}
$pagination.= ($page >= $pages) ? "Next | " : "Next | ";
$pagination.= ($page >= $pages) ? "Last" : "Last";
$pagination.= "</p>\n";
but when i clicked on the 2nd page and then the 3rd page, the result was this:
index.php?menuid=6&page=2&page=3
My other question is, that how to show just the previous two and the next two page numbers like in this one?
This is the php code for the pagination:
$query = mysql_query("SELECT * FROM posts");
$howmuch = 5;
$total = mysql_num_rows($query);
$page = (isset($_GET['page'])) ? $_GET['page'] : 1;
$pages = ceil($total/$howmuch);
$where = ($page-1)*$howmuch;
$active="(SELECT s_id FROM status WHERE s_name='active')";
$sql = "SELECT post_id, post_title, post_content, post_date
FROM posts
WHERE post_s_id=".$active."
ORDER BY post_id DESC
LIMIT {$where}, {$howmuch}";
$result = mysql_query($sql);
$output="";
while ($row = mysql_fetch_assoc($result)) {
$output.="Here are the posts";
}
return $output.$pagination;
!!!UPDATE!!!
I'm sorry, but I forgot to mention, that the posts.php is included in the index.php, and the above code is in the posts.php.
The menu_id is in the code of the index.php, not in the posts.php, but the url is the same.

$_SERVER['REQUEST_URI'] will get everything in the URL, thats why it's adding up all your page vars.
Use
$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'].'?menuid='.$_GET['menuid'].'&page='.$page

Quick function to generate this regardless of the parameters in the url
function getPageUri($page) {
$_GET['page'] = $page;
foreach($_GET as $key => $value ) {
$query_string[] = "$key=$value";
}
return $_SERVER['PHP_SELF'] . '?' . implode('&', $query_string);
}

Related

Check last row from phpmyadmin database with PHP

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..

Some misunderstanding with pagination

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.

Paginate results from a multi variable query mysql database

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.

PHP Pagination Problem

I had search through many websites and tried the different ways provided online, but it cant seen to work. It does not load the information when I click next, last, first, previous. It only loads the first page's result. Please help! Thank you in advance.
function retrieveName($fieldName)
{
$i=1;
if(isset($_GET[$fieldName]))
{
mysql_connect("localhost", "root") or die(mysql_error());
mysql_select_db("intern") or die(mysql_error());
//This checks to see if there is a page number. If not, it will set it to page 1
if (!(isset($pagenum)))
{
$pagenum = 1;
}
//Here we count the number of results
$intern = $_GET[$fieldName];
$data = mysql_query("SELECT p.`internName`, p.`internNRIC`, c.`internSchName` FROM `personaldetails` p, `currentinstitution` c WHERE c.`internNRIC`= p.`internNRIC` AND p.`internName` like '%$intern%' || p.`internNRIC` like '%$intern%' || c.`internSchName` like '%$intern%' GROUP BY p.internNRIC") or die(mysql_error());
$rows = mysql_num_rows($data);
//This is the number of results displayed per page
$page_rows = 1;
//This tells us the page number of our last page
$last = ceil($rows/$page_rows);
//this makes sure the page number isn't below one, or more than our maximum pages
if ($pagenum < 1)
{
$pagenum = 1;
}
elseif ($pagenum > $last)
{
$pagenum = $last;
}
//This sets the range to display in our query
$max = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
PRODUCTION. //This is your query again, the same one... the only difference is we add $max into it
$data_p = mysql_query("SELECT p.`internName`, p.`internNRIC`, c.`internSchName` FROM `personaldetails` p, `currentinstitution` c WHERE c.`internNRIC`= p.`internNRIC` AND p.`internName` like '%$intern%' || p.`internNRIC` like '%$intern%' || c.`internSchName` like '%$intern%' GROUP BY p.internNRIC $max ") or die(mysql_error());
//This is where you display your query results
while($row = mysql_fetch_array( $data_p ))
{
echo $i. ".";
echo " NRIC : ".$row['internNRIC'] ."";
echo "</br><br/>";
echo " Name : ". $row['internName'] . " Name of School :" . $row['internSchName'];
echo "</br><br/>";
$i++;
}
echo "<p>";
// This shows the user what page they are on, and the total number of pages
echo " --Page $pagenum of $last-- <p>";
// First we check if we are on page one. If we are then we don't need a link to the previous page or the first page so we do nothing. If we aren't then we generate links to the first page, and to the previous page.
if ($pagenum == 1)
{
}
else
{
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=1&searchIntern=$intern'> <<-First</a> ";
echo "---Interns Search---";
$previous = $pagenum-1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$previous&searchIntern=$intern'> <-Previous</a> ";
}
//This does the same as above, only checking if we are on the last page, and then generating the Next and Last links
if ($pagenum == $last)
{
}
else
{
$next = $pagenum+1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$next&searchIntern=$intern'>Next -></a> ";
echo "---Interns Search---";
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$last&searchIntern=$intern'>Last ->></a> ";
}
}else echo "Please enter your search.";
}
Not 100% about this, but it looks like you're using a local variable for $pagenum when you want to use either a parameter (good idea) or a global variable such as $_GET['pagenum']. You're also leaving yourself open to SQL injection. Use mysql_real_escape_string on all variables which need to be used in queries (like $intern).
As #cwallenpoole says, it looks like $pagenum is scoped outside of the function, and I'm guessing the function is written assuming that register_globals is on, which is generally a very bad thing. I've seen this cause plenty of issues when moving an old (inherited) site to a new server.
To fix that specific problem, replace:
if (!(isset($pagenum)))
{
$pagenum = 1;
}
with this:
$pagenum = isset($_REQUEST['pagenum']) ?
(int)$_REQUEST['pagenum'] :
1;
This sets $pagenum to the request's pagenum value, and defaults to 1 if the page number isn't in the request. It also casts the value to an int which should at least stop one injection attack vector. The rest of the function is another matter...

paging with php?

hello i want to list contents as 10 contents per page
this is source code for each content
<?
while ($arama=mysql_fetch_array($arama_sonuc)) {
?>
<h4><?=$arama[baslik]?></h4>
<div class="article box">
<div class="article-desc-oku">
<p class="info">Yayınlanma: <strong><?=$arama[eklemetarihi]?></strong><br />
Yazan: <strong>Ronnie C. Lynwood</strong><br /><?=$arama[tiklanma]?> kez okunmuş.<br />
<?php rating_form("$arama[id]"); ?>
</p>
</div>
<?=$arama[spot]?>
</div> <!-- /article -->
I think you should better use a paging class rather than creating your own. This will save a lot of time of yours in next projects too. Your current problem will also be solved. Check this out.
Download Location
It looks like you are using MySQL: You can build a query using the SQL LIMIT command.
For example:
SELECT * FROM myTable LIMIT 5, 10
Will tell MySQL to return only the first ten elements after the 5th row. You can use a parameter on the query string to build an appropriate SQL query to "ask" the database which "page" you want to see.
Here http://php.about.com/od/phpwithmysql/ss/php_pagination.htm you can find a complete code example on pagination. It's also explained very well.
Sorry but I can't offer more just by seeing a snipped of code ...
i used codes below to make pagination
<?
if (isset($_GET['sayfa'])) {
$pageno = $_GET['sayfa'];
} else {
$pageno = 1;
} // if
$query = mysql_query("SELECT count(id) FROM yazilar");
$query_data = mysql_fetch_row($query);
$numrows = $query_data[0];
$rows_per_page = 10;
$lastpage = ceil($numrows/$rows_per_page);
$pageno = (int)$pageno;
if ($pageno > $lastpage) {
$pageno = $lastpage;
} // if
if ($pageno < 1) {
$pageno = 1;
} // if
$limit = 'ORDER BY id DESC LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page;
$query = mysql_query("SELECT * FROM yazilar $limit");
if ($pageno == 1) {
echo " İLK ÖNCEKİ ";
} else {
echo " <a href='{$_SERVER['PHP_SELF']}?sayfa=1'>İLK</a> ";
$prevpage = $pageno-1;
echo " <a href='{$_SERVER['PHP_SELF']}?sayfa=$prevpage'>ÖNCEKİ</a> ";
} // if
echo " ( Sayfa $pageno ) ";
if ($pageno == $lastpage) {
echo " SONRAKİ SON ";
} else {
$nextpage = $pageno+1;
echo " <a href='{$_SERVER['PHP_SELF']}?sayfa=$nextpage'>İLERİ</a> ";
echo " <a href='{$_SERVER['PHP_SELF']}?sayfa=$lastpage'>SON</a> ";
} // if
?>
Let me suggest some existing PHP solutions
Zend_Paginator, loosely coupled can be used stand alone without the whole framework.
If you want to build your own flavour I recommand the SPL countable and Iterator classes.

Categories