473,789 Members | 2,550 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to display 20 results per page, with a next and previous page?

2 New Member
I would like to add 20 offers per page and becuase the database is updated daily. i need a way to allow access to other pages so that all offers will be displayed. i was thinking the next / previous function, but my page count can constantly change so im wanting some way of it automatically only having the amount of pages needed to support the amount of offers. normally i can display anywhere from 100-1000+ offers


code:

<?
session_start() ;
$page="offers";
include"header. php";
include"mysql.p hp";

$_GET['out']=strip_tags($_G ET['out']);
$_GET['out']=mysql_real_esc ape_string($_GE T['out']);
if($_GET['out']!="")
{
mysql_query("up date offers set visits=visits+1 where id={$_GET['out']}",$c);
$geturl=mysql_q uery("select * from offers where id={$_GET['out']}",$c);
$out=mysql_fetc h_array($geturl );
print"
<h2>Please wait..</h2>
<p>
<center>
<meta http-equiv=\"refresh \" content=\"2;url ={$out['url']}/&subid1={$ui['username']}\">
Taking you to the offer...<br>
If this page does not change in 2 seconds, <a href=\"{$out['url']}/&subid1={$ui['username']}\">click here</a>.
</center>
</p>
";
include"side.ph p";
include"footer. php";
exit;
}
else
{
$money=0;
$getoffercash=m ysql_query("sel ect * from offers where active=1",$c);
while($oc=mysql _fetch_array($g etoffercash))
{
$money=$money+$ oc['reward'];
}
}
if($_SESSION['loggedin']==1)
{
$refer="<br>Ref er your friends: $siteurl/?ref={$ui['username']}<br>and receive an instant $$refbonus bonus per referral!";
}
else
{
$refer="";
}
?>


<h2>Free Offers</h2>
<p class="post-by"><a href="how.php?r ef=<? print"$ref"; ?>">not sure what to do?</a></p>
<p><center>Poss ible Earnings: $<?=$money;?><? =$refer;?></center></p>
<table width="90%">
<tr>
<th colspan="0" align="center">
Free To Complete
</th>
</tr>
<tr>
<th width="25%">Off er</th>
<th width="10%">Dat e</th>
<th width="45%">Des cription</th>
<th width="10%">Rew ard</th>
<th width="10%">Com pleted?</th>
</tr>
<?

$_GET['offer']=strip_tags($_G ET['offer']);
$_GET['offer']=mysql_real_esc ape_string($_GE T['offer']);
$type="free";
$getoffers=mysq l_query("select * from offers where `type`='$type' and active=1 order by reward desc",$c);

if(mysql_num_ro ws($getoffers)= =0)
{
print"<tr><td colspan=\"3\">T here are currently no free offers available</td></tr>";
}
else
{

while($off=mysq l_fetch_array($ getoffers))
{
$desc=$off['desc'];
$date=$off['date'];

if($_GET['offer']==$off['id'])
{
$color="style=\ "background-color: #a2e250;\"";
$front="<font color=\"black\" ><b>";
$back="</b></font>";
}
else
{
$color="";
$front="";
$back="";
}
if($_SESSION['loggedin']==1)
{
$form="<form class=\"searchf orm2\" action=\"comple ted.php\" method=\"get\"> <input type=\"hidden\" name=\"offer\" value=\"{$off['id']}\"><input type=\"submit\" class=\"button\ " value=\"Done!\" ></form>";
}
else
{
$form="<font color=\"red\">< b>Please Login</b></font>";
}


$checkpend=mysq l_query("select * from pending where offer_id={$off['id']} and user_id='{$_SES SION['userid']}' and denied=0",$c);
$checkcompleted =mysql_query("s elect * from completed where offer_id={$off['id']} and user_id='{$_SES SION['userid']}'",$c);

if(mysql_num_ro ws($checkpend)! =0)
{
$form="<font color=\"orange\ "><b>Pendin g</b></font>";
}
else if(mysql_num_ro ws($checkcomple ted)!=0)
{
$form="<font color=\"green\" ><b>Completed </b></font>";
}

if(mysql_num_ro ws($checkpend)! =0 || mysql_num_rows( $checkcompleted )!=0)
{
$link="$front{$ off['name']}$back";
}
else
{
$link="<a href=\"offers.p hp?out={$off['id']}\" target=\"_blank \" title=\"Availab le in: {$off['countries']}\">$front{$o ff['name']}$back</a>";
}

print"
<tr $color>
<td width=\"100%\"> $link</td>
<td align=\"center\ ">$date</td>
<td align=\"center\ ">$desc</td>
<td align=\"center\ ">$front\${ $off['reward']}$back</font></td>
<td align=\"center\ ">$form</td>
</tr>
";
}
}

?>
</table>
<?
include"side.ph p";
include"footer. php";
?>
Feb 6 '11 #1
3 6352
HaLo2FrEeEk
404 Contributor
First off, please use code tags in the future, they make code a lot easier to read on the forum because it preserves formatting.

As for your question, there are a few aspects. To get a limited set of results from the database use the LIMIT command in your query. Example:

SELECT * FROM `table` ORDER BY `id` DESC LIMIT 0, 20

This query would select the most recent 20 results. You need something to sort it by though, in this example I'm sorting by id, id would be a column set to auto increment, something where newer rows have a higher value than older rows.

Next, you need to count how many rows there are total, for this you could use the count() selector:

SELECT count(*) FROM `table`

This will allow you to calculate how many pages you need. For example, if you are displaying 20 results per page and you have 50 results in the table, then you need 3 pages. The first 2 pages would have 20 results and the last page would have 10. I'd recommend setting a variable with the number of results you want per page, you can use this variable in your first SELECT query, the one with the limit command, you can also use it in your calculations.

Finally, you need a GET variable that represents which page you're currently on.

Expand|Select|Wrap|Line Numbers
  1. $rpp = 20;
  2. $page = @$_GET['page'];
  3. if(!$page) {
  4.   $page = 0;
  5.   }
  6.  
  7. $sql = mysql_query("SELECT * FROM `table` LIMIT ".($rpp * $page).", ".$rpp) or die("Error: " . mysql_error());
  8. // Do something with your results
  9.  
  10. $sql = mysql_query("SELECT count(*) FROM `table`") or die("Error: " . mysql_error());
  11. $res = mysql_result($sql, 0);
  12. $totalpages = ceil($res / $rpp); // ceil() rounds fractions up to the next whole number
Hopefully I've given you enough to start with.
Feb 7 '11 #2
christy jones
2 New Member
Ive added the Limit 20,30 to the command line, but im noticing that when i tried to change the values, the data is not showing the correct amt. i only see my first change of limit 0,20 and nothing else. ive also followed the guide for displaying pages and am not showing any links to the pages, im also receiving no errors. would be happy to provide link to site through an email

Expand|Select|Wrap|Line Numbers
  1. $_GET['offer']=strip_tags($_GET['offer']);
  2. $_GET['offer']=mysql_real_escape_string($_GET['offer']);
  3. $type="free";
  4. $getoffers=mysql_query("select * from offers where `type`='$type' and active=1 order by reward desc LIMIT 20,30",$c);
  5. if (isset($_GET['pageno'])) {
  6.    $pageno = $_GET['pageno'];
  7. } else {
  8.    $pageno = 1;
  9. } // if
  10. $query = "SELECT count(*) FROM table WHERE ...";
  11. $result = mysql_query($query, $db) or trigger_error("SQL", E_USER_ERROR);
  12. $query_data = mysql_fetch_row($result);
  13. $numrows = $query_data[0];
  14. $rows_per_page = 25;
  15. $lastpage      = ceil($numrows/$rows_per_page);
  16. $pageno = (int)$pageno;
  17. if ($pageno > $lastpage) {
  18.    $pageno = $lastpage;
  19. } // if
  20. if ($pageno < 1) {
  21.    $pageno = 1;
  22. } // if
  23. $limit = 'LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page;
  24. $query = "SELECT * FROM table $limit";
  25. $result = mysql_query($query, $db) or trigger_error("SQL", E_USER_ERROR);
  26. ... process contents of $result ...
  27. if ($pageno == 1) {
  28.    echo " FIRST PREV ";
  29. } else {
  30.    echo " <a href='{$_SERVER['PHP_SELF']}?pageno=1'>FIRST</a> ";
  31.    $prevpage = $pageno-1;
  32.    echo " <a href='{$_SERVER['PHP_SELF']}?pageno=$prevpage'>PREV</a> ";
  33. } // if
  34. echo " ( Page $pageno of $lastpage ) ";
  35. if ($pageno == $lastpage) {
  36.    echo " NEXT LAST ";
  37. } else {
  38.    $nextpage = $pageno+1;
  39.    echo " <a href='{$_SERVER['PHP_SELF']}?pageno=$nextpage'>NEXT</a> ";
  40.    echo " <a href='{$_SERVER['PHP_SELF']}?pageno=$lastpage'>LAST</a> ";
  41. } // if
  42.  
  43.  
  44.  
Feb 8 '11 #3
HaLo2FrEeEk
404 Contributor
I gave you the tools and knowledge you need to solve problem, I won't write the code for you. You need to go back and read my post.

the LIMIT command in a query looks like this:

LIMIT 0, 20

That means that thequery will get 20 results starting from the 0th (first) result, so it will get results 0-19. You need to use your page variable to determine what value you start from, so if you're on page 1, then your limit will look like it does above, if you're on page 2 then it will be LIMIT 20, 20, page 3, LIMIT 40, 20. Make sense? You calculate this by having a variable where you specify how many results you want to display per page:

Expand|Select|Wrap|Line Numbers
  1. $page = @$_GET['page']; // Gets the current page
  2. if(!$page)
  3.   $page = 0; // Defaults the pae to 0 if it's not provided.
  4. $rpp = 20; // This is the number of results per page
  5.  
  6. // This query sets the limit to start at the page number multipled by the results per page, and to get $rpp results.
  7. $sql = "SELECT * FROM `table` ORDER BY `reward` LIMIT ".($pae * $rpp)).", ".($rpp);
Please note that this isn't plug n' play code, it's an example that you will need to understand before you can use it.

As for the pages, here's a simple way to show a previous and next link:

Expand|Select|Wrap|Line Numbers
  1. // You've already got your $page variable
  2. $sql = mysql_query("SELECT count(*) FROM `table`") or die("Error: ".mysql_error());
  3. $numrows = mysql_result($sql, 0);
  4. $numpages = ceil($numrows / $rpp);
  5.  
  6. if($page <= $numpages) {
  7.   echo "<a href=\"?page=".($page + 1)."\"><< Previous</a>";
  8.   }
  9. if($page > 0) {
  10.   echo "<a href=\"?page=".($page - 1)."\">Next >></a>";
  11.   }
Once again, this is example code, you need to understand HOW it works and not just THAT it works, otherwise you won't learn anything and you'll be right back here the next time you have a problem like this. Understanding and learning why and how the code works is the first step to furthering your own knowledge and ability, it's how I've gotten as good as I am at this kind of thing.
Feb 9 '11 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

8
3722
by: joe | last post by:
Can anyone help me out by either telling me how to get to the result i need or by pointing me to some documentation about the following question: A certain query to a database give me eg 100 results: $query = "select id, name, addr1, addr2, city from mytable where id=" ..$id; $connection = mysql_connect(etc etc) ....
3
3058
by: Marcel | last post by:
Hello, I'm working on a search application for my website. The website contains a lot of pictures, and a search should return clickable thumbnails. No problems there. My problem started when I wanted to build in NEXT and PREVIOUS buttons, so that you only get 5 or 10 or 20 (I haven't made up my mind yet) thumbnails at a time. I use a SQL LIMIT statement to achieve that. After displaying the first 5 pictures I would like to see the next 5,...
11
8324
by: middletree | last post by:
I need to capture the previous page's URL. I thought I could find a way to do it with client-side code, but I have been unable to find a way to do that, so perhaps there's an ASP solution. Please note that this is for an Intranet app, so users will be coming to a particular page from another page. Specifically, I need the URL including the GET data that comes after the ".asp" part. Any code which can help is welcome. IE-specific is...
2
1621
by: Lee Connell | last post by:
Hi, How do I create a page that has the potential of grabbing a lot of results and displaying the result set in a per number basis. For example a google search will display say 15 pages with a next and previous that will return the next 15 pages. How would I do this in ASP.NET with a result set I query from my database. thanks.
3
2565
by: g3000 | last post by:
I have a problem with a Visual Studio 2005 web project. I have two pages. SelectProject.aspx and ShowProject.aspx The first page ( SelectProject.aspx) has two drop down lists. After the user selects the value in the first drop list the second filters. That works fine. But when I click the run report button to pass the data to the
1
1324
by: alanb | last post by:
Hi, I need help with only displaying a set of answers / feedback on the following site: I use Javascript to to the calculations and just pass the value through using hidden fields to the results page, this question will make more sense if I show you the pages I am working on: http://golfperformanceacademy.com/handicap/technical.php if you go through the set of questions, that being Technical, Fitness, Nutrition and Psychology you...
8
3838
pentahari
by: pentahari | last post by:
Redirect to login page if session("UserName") is expired when the page useraccount.aspx load event My useraccount.aspx code : If Session("UserName") Is Nothing Then Response.Redirect("../login/login.aspx") End If The above code works correctly. but my question is the user enter the correct username and password in the login.aspx page . it will automatically redirect to previous page (useraccount.aspx; useraccount.aspx is the...
3
3562
oranoos3000
by: oranoos3000 | last post by:
hi i'm a beginer javascript would you please help me i d like to findout this page has next page or previous page in history object i use this line of code if(window.history.length>0) and with this line code indentify that exist else page that visited via this page but i want to findout this pages is previous page or nextpage? thanks very much for your help
3
4662
by: rjlorenzo | last post by:
Hi to all, I have created a survey page that consists of 4 pages 10 question on each page. Each question are just answer using a radio button. Now my problem is i have to retain all the answer/value of radio button even the user click previous page then going back to current page. appreciate any idea please. thank you in advance
1
3469
by: mfaisalwarraich | last post by:
hi everybody, im trying to make next and previous buttons. im displaying record based on a search. when any image on the search results is clicked then dat image opened in a new page with details about dat imgae on a seperate page. lets say this image as a coupon. now im trying to navigate to next and previous records without going back. while($resultSet = mysql_fetch_assoc($que)){ $np = $rs; } $_SESSION= $np;
0
9663
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10404
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10136
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9016
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7525
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6765
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5548
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3695
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2906
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.