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.
Related
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);
}
I've come across a problem - but any help would be appreciated.
When I query the database using the results posted from a form, the pagination works initially i.e. for the first 10 records but when I click on the 2 hyperlink of the pagination for the second page of results it loses the $_POST variable and returns to the full data set.
What is the best way of keeping these variables available for the second (and further) pages?
thanks for reply:
still i have a problem, can any one help me please , the below is my complete php file
thanks in advance
<html>
<head>
<link rel="stylesheet" type="text/css"
href="design.css">
</head>
<body>
<?php
include("header.php");
?>
<center>
<div id="content" class="frm">
<a href='admin.php' style='float:left'>Back!</a>
<h2>Search Result</h2>
<br><br>
<?php
include("../config.inc");
$find=$_GET['find'];
// get page no and set it to page variable, if no page is selected so asign first page bydefualt
if (isset($_GET["page"])){
$page = $_GET["page"];
}
else {
$page=1;
}
// count all record in this table then divide it on 10 in order to find the last page----- every page has 10 record display
$sql = "SELECT COUNT(*) FROM tt where TTT='$find' ";
$rs_result = mysql_query($sql);
$row = mysql_fetch_row($rs_result);
$total_records = $row[0];
$total_pages = ceil($total_records / 2);
// this line check that page no must be in integer format
$page = (int)$page;
if ($page > $total_pages) {
$page = $total_pages;
} // if
if ($page < 1) {
$page= 1;
} // if
$start_from = ($page-1) * 2;
$q=mysql_query("select * from tt where TTT='$find' order by ID limit $start_from,2");
$c=mysql_query("select count(*) from tt where TTT='$find'");
echo "<center>".mysql_result($c,0)."Filtered</center>";
echo "<center>";
echo "<table border='2' bgcolor=#CCCCCC>
<tr>
<th>TTT</th>
<th>Enroll Date</th>
<th>Gradution Date</th>
<th>ID</th>
</tr>";
while($row=mysql_fetch_array($q))
{
echo "<tr>";
echo "<td>".$row['TTT']."</td>";
echo "<td>".$row['Enroll_Date']."</td>";
echo "<td>".$row['Graduation_Date']."</td>";
echo "<td>".$row['ID']."</td>";
}
echo "</table>";
echo "<center>";
// paginatio start here
if ($page== 1) {
echo " << < ";
} else {
echo " <a href='{$_SERVER['PHP_SELF']}?page=1'><<</a> ";
$prevpage = $page-1;
echo " <a href='{$_SERVER['PHP_SELF']}?page=$prevpage'><</a> ";
} // if
echo " ( Page [$page] of [$total_pages] ) ";
if ($page == $total_pages) {
echo " > >> ";
} else {
$nextpage = $page+1;
echo " <a href='{$_SERVER['PHP_SELF']}?page=$nextpage'>></a> ";
$lastpage=$total_pages;
echo " <a href='{$_SERVER['PHP_SELF']}?page=$lastpage'>>></a> ";
} // if
?>
</div>
</center>
<?php
include("footer.php");
?>
</body>
</html>
The best practice says to not use POST method if your query doesn't alter the state of your system. For example, in your case I wouldn't submit a POST request but I'd use GET.
That way your pagination links should preserve your query parameters.
Don't use POST in the first place. POST is for sending data to be acted on. GET is for sending data that describes what you want to read. If you are paginating, then you are reading things.
Then make sure your links contain all the data you need to describe what it is you want the second (or third or etc) page to contain.
Its usefull to get a pre-written pagination class if you are inexperienced making one yourself. (if not ignore this awnser)
You could use something like this
http://www.catchmyfame.com/2011/10/23/php-pagination-class-updated-version-2/
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...
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.
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.