Skip to page content or skip to Accesskey List.
Search evolt.org
evolt.org login: or register

Work

Main Page Content

Multiple Pages With PHP

Rated 4.33 (Ratings: 24) (Add your rating)

Log in to add a comment
(54 comments so far)

Want more?

 
Picture of jesteruk

Jester uk

Member info | Full bio

User since: December 22, 2001

Last login: December 22, 2001

Articles written: 6

Ever wondered how the search engines split your results up into those tidy pages with the "next" and "previous" links? Ever had a huge list of results you've wanted to make more organised? This article will show you how.

The Benefits

The first thing to consider when designing a website is user-friendliness. If you visit a website that's difficult to use, poorly constructed and you can't get to where you want to go fast -- what do you do? You hit that little "X" in the top-right corner, and that's exactly what visitors to your website will do if you don't take the time to make it easy to use. Splitting your results up into smaller, more managable chunks will make it easier for your visitors to browse through them.

OK, What Do I Need?

We're going to use PHP to query a MySQL database, manage the results and print a pre-defined limit of results onto each of the multiple pages. It'd be handy if you had a basic grasp of PHP and SQL -- if not visit the official PHP website and have a look at their tutorials. Experience with using PHP to interact with and handle data retrieved from a MySQL database is essential for you to understand this article. If you don't know what i'm talking about, go learn it; it's where web development is going. Oh, access to a PHP interpreter and a MySQL database would come in handy also.

Let's Do It

Database Connection

Ok firstly let's connect to your database. Obviously you would put your correct information in here. See the below code:

<?
$db_addr = 'localhost';		// address of MySQL server.
$db_user = 'user';		// Username to access server.
$db_pass = 'password';		// Password access server.
$db_name = 'MyDatabase';	// Name of database to connect to.
$connect = @mysql_connect("$db_addr", "$db_user", "$db_pass");

if (!($connect)) // If no connect, error and exit().
{
     echo("<p>Unable to connect to the database server.</p>");
     exit();
}

if (!(@mysql_select_db($db_name))) // If can't connect to database, error and exit().
{
     echo("<p>Unable to locate the $db_name database.</p>");
     exit();
}

If you don't understand the above maybe you should stop now and read a basic PHP tutorial. Basically, all it does is use your information to try and make a connection to the database, if a connection to the database server cannot be made, it errors and exits. If the specified database cannot be found, it errors and exits.

Define Some Variables

Now we need to define some variables, sort out how many results we want per-page and construct our database query, look at the code below, then i'll explain:

if (!($limit)){
     $limit = 10;} // Default results per-page.

if (!($page)){
     $page = 0;} // Default page value.

$numresults = mysql_query("SELECT * FROM your_table WHERE name LIKE '%". $query ."%'"); // the query.

$numrows = mysql_num_rows($numresults); // Number of rows returned from above query.

if ($numrows == 0){
     echo("No results found matching your query - $query"); // bah, modify the "Not Found" error for your needs.
     exit();}

Now we have some variables to work with. If $limit is not already specified (for example in the query string) then it will have the value of 10. If $page is not already specified in the query string it will be set to 0. $limit is used to control the number of results per-page, we are going to add to this and allow the user to control it. $page is used to let the script know which page, which chunk of results to show on each given page. Now we have the limit per-page, and the number of results that need to be displayed. Bear with me this will all become clearer soon.

The Math

Now we need to calculate the number of results pages there will be. Say we have 35 results, and we want to split them into 10 per-page, there will be 4 results pages. We're also going to add some visual fancies, take a look at the code:

$pages = intval($numrows/$limit); // Number of results pages.

// $pages now contains int of pages, unless there is a remainder from division.

if ($numrows % $limit) {
$pages++;} // has remainder so add one page

$current = ($page/$limit) + 1; // Current page number.

if (($pages < 1) || ($pages == 0)) {
$total = 1;} // If $pages is less than one or equal to 0, total pages is 1.

else {
$total = $pages;} // Else total pages is $pages value.

$first = $page + 1; // The first result.

if (!((($page + $limit) / $limit) >= $pages) && $pages != 1) {
$last = $page + $limit;} //If not last results page, last result equals $page plus $limit.
 
else{
$last = $numrows;} // If last results page, last result equals total number of results.

OK let's slow down and have a look at what we have done so far:

  • Database Connection: Establish that the script can connect to the MySQL database.
  • Define Variables: Tell script how many results per-page we want, query the database and find total result we're going to be dealing with.
  • The Math: Calculate the number of pages we'll be dealing with. Code in some extra little bits, the current page number (to allow us to show "page 1 of 3"), the first result on current page, the last result on current page.
  • Visual Tid-Bits

    Now let's write the code that'll show the user what page they're on and what set of results they're viewing, see the code:

    //escape from PHP mode.
    ?>
    <html>
    <head>
    <title>Search Results for <?=$query?></title>
    </head>
    <body>
    <center><h2>Search Results for <?=$query?></h2></center>
    <table width="100%" border="0">
     <tr>
      <td width="50%" align="left">
    Results <b><?=$first?></b> - <b><?=$last?></b> of <b><?=$numrows?></b>
      </td>
      <td width="50%" align="right">
    Page <b><?=$current?></b> of <b><?=$total?></b>
      </td>
     </tr>
     <tr>
      <td colspan="2" align="right">
    &nbsp;
      </td>
     </tr>
     <tr>
      <td colspan="2" align="right">
    Results per-page: <a href="<?=$PHP_SELF?>?query=<?=$query?>&page=<?=$page?>&limit=5">5</a> | <a href="<?=$PHP_SELF?>?query=<?=$query?>&page=<?=$page?>&limit=10">10</a> | <a href="<?=$PHP_SELF?>?query=<?=$query?>&page=<?=$page?>&limit=20">20</a> | <a href="<?=$PHP_SELF?>?query=<?=$query?>&page=<?=$page?>&limit=50">50</a>
      </td>
     </tr>
    </table>
    <?
    //Go back into PHP mode.
    

    Now we have the start of the results page that the user will actually see. Let's say again that the query returned 35 results, this bit of code would display at the top of the page:

    Results 1 - 10 of 35 Page 1 of 4
     
    Results per-page: 5 | 10 | 20 | 50


    Now that the user can see the page they're on and the set of results they're viewing, we need to display the actual results to them, and show the links to each result page.

    Displaying The Results

    Now we're going to show the pre-defined limit of results on the current page, see the below code:

    // Now we can display results.
    $results = mysql_query("SELECT * FROM your_table WHERE name LIKE '%". $query ."%' ORDER BY name ASC LIMIT $page, $limit");
    while ($data = mysql_fetch_array($results))
    {
    ?>
    <p><a href="<?=$data["url"]?>" title="<?=$data["name"]?>"><?=$data["name"]?></a> - <?=$data["description"]?></p>
    <?
    }
    

    Notice the MySQL query, we've modified it alittle. Instead of just selecting all the rows, we select them, order them alphabetically, limit them according to the relevant page and then display each row from the query. Bear in mind, this is an hypothetical situation. Your database table may not contain a url, name or description column, i am just improvising, i'm sure you can edit the script to meet your own needs and database. Read on....

    Linking To Other Pages

    Now the final part of the code, linking to each of the results pages so the user can browse through them easily, see the below code:

    ?>
    <p align="center">
    <?
    if ($page != 0) { // Don't show back link if current page is first page.
    $back_page = $page - $limit;
    echo("<a href=\"$PHP_SELF?query=$query&page=$back_page&limit=$limit\">back</a>    \n");}
    
    for ($i=1; $i <= $pages; $i++) // loop through each page and give link to it.
    {
     $ppage = $limit*($i - 1);
     if ($ppage == $page){
     echo("<b>$i</b>\n");} // If current page don't give link, just text.
     else{
     echo("<a href=\"$PHP_SELF?query=$query&page=$ppage&limit=$limit\">$i</a> \n");}
    }
    
    if (!((($page+$limit) / $limit) >= $pages) && $pages != 1) { // If last page don't give next link.
    $next_page = $page + $limit;
    echo("    <a href=\"$PHP_SELF?query=$query&page=$next_page&limit=$limit\">next</a>");}
    ?>
    </p>
    </body>
    </html>
    

    The above code checks to see if the current page is the first page. If it is, it bypasses the "previous" link. It then loops through each page and provides a link to them, except if the link number is that of the current page, then it displays a text number. It then checks to see if the current page is the last page, if it is, it bypasses the "next" link.

    OK there we have it, a simple script that will query the database, find the number of rows affected by the query, calculate the number of pages, display to the user where they are amongst the results and provide links to the other results pages, easier than you thought, eh? Let's have a look at the full code.

    The Finished Script

    <?
    $db_addr = 'localhost';		// address of MySQL server.
    $db_user = 'user';		// Username to access server.
    $db_pass = 'password';		// Password access server.
    $db_name = 'MyDatabase';	// Name of database to connect to.
    $connect = @mysql_connect("$db_addr", "$db_user", "$db_pass");
    
    if (!($connect)) // If no connect, error and exit().
    {
    echo("<p>Unable to connect to the database server.</p>");
    exit();
    }
    
    if (!(@mysql_select_db($db_name))) // If can't connect to database, error and exit().
    {
    echo("<p>Unable to locate the $db_name database.</p>");
    exit();
    }
    
    if (!($limit)){
    $limit = 10;} // Default results per-page.
    if (!($page)){
    $page = 0;} // Default page value.
    $numresults = mysql_query("SELECT * FROM your_table WHERE name LIKE '%". $query ."%'"); // the query.
    $numrows = mysql_num_rows($numresults); // Number of rows returned from above query.
    if ($numrows == 0){
    echo("No results found matching your query - $query"); // bah, modify the "Not Found" error for your needs.
    exit();}
    
    $pages = intval($numrows/$limit); // Number of results pages.
    
    // $pages now contains int of pages, unless there is a remainder from division.
    
    if ($numrows%$limit) {
    $pages++;} // has remainder so add one page
    
    $current = ($page/$limit) + 1; // Current page number.
    
    if (($pages < 1) || ($pages == 0)) {
    $total = 1;} // If $pages is less than one or equal to 0, total pages is 1.
    
    else {
    $total = $pages;} // Else total pages is $pages value.
    
    $first = $page + 1; // The first result.
    
    if (!((($page + $limit) / $limit) >= $pages) && $pages != 1) {
    $last = $page + $limit;} //If not last results page, last result equals $page plus $limit.
     
    else{
    $last = $numrows;} // If last results page, last result equals total number of results.
    
    //escape from PHP mode.
    ?>
    <html>
    <head>
    <title>Search Results for <?=$query?></title>
    </head>
    <body>
    <center><h2>Search Results for <?=$query?></h2></center>
    <table width="100%" border="0">
     <tr>
      <td width="50%" align="left">
    Results <b><?=$first?></b> - <b><?=$last?></b> of <b><?=$numrows?></b>
      </td>
      <td width="50%" align="right">
    Page <b><?=$current?></b> of <b><?=$total?></b>
      </td>
     </tr>
     <tr>
      <td colspan="2" align="right">
    &nbsp;
      </td>
     </tr>
     <tr>
      <td colspan="2" align="right">
    Results per-page: <a href="<?=$PHP_SELF?>?query=<?=$query?>&page=<?=$page?>&limit=5">5</a> | <a href="<?=$PHP_SELF?>?query=<?=$query?>&page=<?=$page?>&limit=10">10</a> | <a href="<?=$PHP_SELF?>?query=<?=$query?>&page=<?=$page?>&limit=20">20</a> | <a href="<?=$PHP_SELF?>?query=<?=$query?>&page=<?=$page?>&limit=50">50</a>
      </td>
     </tr>
    </table>
    <?
    //Go back into PHP mode.
    
    // Now we can display results.
    $results = mysql_query("SELECT * FROM your_table WHERE name LIKE '%". $query ."%' ORDER BY name ASC LIMIT $page, $limit");
    while ($data = mysql_fetch_array($results))
    {
    ?>
    <p><a href="<?=$data["url"]?>" title="<?=$data["name"]?>"><?=$data["name"]?></a> - <?=$data["description"]?></p>
    <?
    }
    ?>
    <p align="center">
    <?
    if ($page != 0) { // Don't show back link if current page is first page.
    $back_page = $page - $limit;
    echo("<a href=\"$PHP_SELF?query=$query&page=$back_page&limit=$limit\">back</a>    \n");}
    
    for ($i=1; $i <= $pages; $i++) // loop through each page and give link to it.
    {
     $ppage = $limit*($i - 1);
     if ($ppage == $page){
     echo("<b>$i</b> \n");} // If current page don't give link, just text.
     else{
     echo("<a href=\"$PHP_SELF?query=$query&page=$ppage&limit=$limit\">$i</a> \n");}
    }
    
    if (!((($page+$limit) / $limit) >= $pages) && $pages != 1) { // If last page don't give next link.
    $next_page = $page + $limit;
    echo("    <a href=\"$PHP_SELF?query=$query&page=$next_page&limit=$limit\">next</a>\n");}
    ?>
    </p>
    </body>
    </html>
    

    So This Is Just a Simple Search Script?

    Absolutely not. This script could perform a myriad of uses. Say you had a "downloads" table in your database containing a list of programs. You want to display just the "programming" related software to your user but there are many programs in this category which would generate a huge page of links. With a slight modification to the database query you could display these programs in neat multiple pages which are user-friendly and easily navigable for your visitor. Many sites these days are built around a search-type script, give it a try for yourself.

    Expandable

    Why not see what ideas you can come up with? How about links on the page that allow your visitor to control how the results are ordered, by name, by date added to the database, by id? How about allowing them to reverse the listing? How about adding to the script to allow them different search actions, exact match or a vague match? The list is endless. Stick a conditional in the script, if the $query variable exists run the above script. If not display a form allowing you to enter a query, so the $query variable contains data and the script is run. This isn't a ready-run-script, it will take some modifiying. Play around!

    Bibliography

    If you wish to get deeper into this ever-popular partnership between PHP and MySQL, visit a couple of sites:

  • PHP's MySQL Functions
  • MySQL Website


  • And don't forget, have any questions? Need any help? Ask us.

    I just like messing around with web design stuff, just a hobby.

    Particularly perl, PHP and SQL.

    http://www.free2code.net/

    really nice

    Submitted by Martin Tsachev on January 2, 2002 - 06:15.

    Your code is great but you could consider changing

    if ( !$page ) { $page = 0 }

    with

    if ( !$page or $page < 0 ) { $page = 0 }

    And also I would never send any database query through the GET method and just send it to the database, you can consider using a simple if .. elseif .. rathar than this

    I hope you don't mind I'm using your code, if you have any conditions for this please contact me

    login or register to post comments

    Just double-checking.

    Submitted by gb on January 2, 2002 - 08:39.

    In the code you have the following piece of logic:

    if (($pages &lt; 1) || ($pages == 0)) {


    What is the difference between this and simply

    if ( $pages &lt; 1 ) {


    since 0 is less than 1? Is this a leftover of perhaps some debugging you did or am I unaware of some goofyness of PHP that requires the evaluation to be written as you have?

    login or register to post comments

    Of course

    Submitted by jesteruk on January 2, 2002 - 14:49.

    nah mate, i suppose you could just have if($pages < 1). Would make the code a few bytes smaller :)

    The code isn't perfect, i'm sure you all can improve and come up with your own ideas for it, it's just a bit of code i wrote to put up on my site (before i learned the hosting is going to be cancelled), thought i'd share it with you all.

    shaggy, you can use it if you want to, there are no terms of use or anything.

    -J

    login or register to post comments

    just rewriting the code for 10 minutes

    Submitted by Martin Tsachev on January 3, 2002 - 06:10.

    OK this is a better one I don't consider this final revision

    This also can be changed from

    $current = ($page/$limit) + 1; // Current page number.

    to
    $current = intval($page/$limit) + 1; // Current page number.
    to make output a bit nicer

    You don't want to display something like Page 1.2 of 2 do you?

    login or register to post comments

    Some changes

    Submitted by antileon on January 3, 2002 - 07:12.

    I like this approach better:

    if (!isset($page) || $page < 0) {
      foo
    }

    since this is the correct way to supress error messages from PHP. (E_NOTICE on)

    And I would use this SQL query:

    SELECT COUNT(*) FROM foo WHERE bar...

    since it's more optimized and faster than allocating space for the results you're not going to return anyway.

    Other than that, it's a great tutorial. There are similar at www.phpbuilder.com if someone is interested.

    login or register to post comments

    aye...

    Submitted by jesteruk on January 8, 2002 - 19:29.

    points well made, hope it works ok for you. Alot of nifty modifications can be made ;)

    login or register to post comments

    Cold Fusion?

    Submitted by oiboi on January 9, 2002 - 18:12.

    Hey what about doing this in CF? Ive found some examples... but it kinda needs some explaining?

    login or register to post comments

    Can you?

    Submitted by jesteruk on January 10, 2002 - 17:58.

    I don't know cold fusion mate lol

    I've never really looked into it, i played around with perl for a while, then i had a go at PHP and i liked it, no need to learn another one, i'm still exploring PHP, one at a time for me.

    You should have a go at it though dude, alot of people would be interested i reckon.

    -J

    login or register to post comments

    Absolute Links?

    Submitted by conoroleary on February 11, 2002 - 14:05.

    The line of code;
    $data["url"]
    returns a relative link (for me anyway). Any ideas on how to change this?

    login or register to post comments

    well...

    Submitted by jesteruk on February 11, 2002 - 15:19.

    I'm afraid that isn't down to the script is it? That's down to you storing the links in your database in relative form. If you want absolute links to be stored in $data["url"] then have absolute links in your database. Obviously, if the search results point the user to another site, it'll have to be an absolute link or they'll get a 404, review your DB.

    login or register to post comments

    Condtional mysql query

    Submitted by roshni_jen on March 10, 2002 - 13:22.

    Hello, I have a form that allows people to speify upto 3 areas where there may be jobs in the UK, however some may only specify 1 or 2 areas so i have to account for them. They also have a drop down menu to choose what type of job...


    I have the below code and it seems to only work when area1 is selected...if area2 or area3 are selected from the drop down menu it gives me all the results in the Database...


    please help if you can? Below is my php code:


    if ($type)
    {
    $sql="SELECT * FROM $dbtable";
    $sql.=" WHERE type = '$type'";
    }



    if ($area1)
    {
    if ($sql=="SELECT * FROM $dbtable")
    {
    $sql.=" WHERE area = '$area1'";
    }else
    {
    $sql.=" OR area = '$area1";
    }
    }



    if ($area2)
    {|
    if ($sql=="SELECT * FROM $dbtable")
    {
    $sql.=" WHERE area = '$area2'";
    }else
    {
    $sql.=" OR area = '$area2";
    }
    }



    if ($area3)
    {
    if ($sql=="SELECT * FROM $dbtable")
    {
    $sql.=" WHERE area = '$area3'";
    }else
    {
    $sql.=" OR area >= '$area3'";
    }
    }



    if ($type)
    {
    if ($sql=="SELECT * FROM $dbtable")
    {
    $sql.=" WHERE jtype = '$stype'";
    }else
    {
    $sql.=" AND jtype = '$stype'";
    }
    }

    login or register to post comments

    manually cutting off

    Submitted by Thermite on April 4, 2002 - 18:23.

    Hey, i'm pretty much a php newbie, but i understand what is listed here. However, for my website, i need to be able to tell the database when to cut off and make a second page. Is there any code i can use from inside the data entry form to tell the database to break to a new page? thanks lots

    login or register to post comments

    Great, can be modified to suit anybody's needs

    Submitted by thuresson on May 8, 2002 - 07:26.

    I have tried similar scripts for search pages before and this is the best one I have found so far. The only thing I'm not too happy about is if the search returns a lot of links. I use five results per page and with 240 matches that will make the search result to be split up on 48 pages. Ofcourse it would be possible to tweak the script so as to only link to the first ten pages or so.

    It took me hours to adapt the script to my needs but I'm very happy with the result.

    Click here to see how I used the script in an image gallery

    login or register to post comments

    PEAR implementation

    Submitted by Martin Tsachev on May 13, 2002 - 15:33.

    A similar functionality is now available as a stable PEAR package. It is full of deprecated code though that is useless as it is already implemented in PEAR::DB nevertheless it is a good choice if you use PEAR::DB for database access.

    login or register to post comments

    found a solution

    Submitted by Thermite on May 13, 2002 - 15:41.

    first off, i solved the problem, thanks alot. however, i found a better system =D. its from the guy who runs DevArticles.com killer CMS system, i'll give the link once it's released. should be anyday now

    login or register to post comments

    Reverse results?

    Submitted by MDixon on May 23, 2002 - 13:54.

    Is it possible (or fairly easy) to reverse the results? So that the most recent row of a table is shown first? Thanks for any input.

    login or register to post comments

    Re: Reverse results

    Submitted by Martin Tsachev on May 23, 2002 - 15:57.

    Yes of course look in the MySQL manual for the ORDER BY clause.

    login or register to post comments

    Re: Reverse results

    Submitted by Martin Tsachev on May 23, 2002 - 15:57.

    Yes of course look in the MySQL manual for the ORDER BY clause.

    login or register to post comments

    Page links just like Google at the bottom

    Submitted by phpoo on July 16, 2002 - 13:40.

    This script tied in very easily and within minutes. Much thanx to the author. The only thing I needed to change was limiting the page results at the bottom. I only added two lines of code.

    All I added to make the page links at the bottom show +5 or -5 from the current page was

    $limitnum = 50; // this is equilavent to 5 pages if your $limit is set to 10. If your $limit is set to 15 then 75 would be equivalent to 5 pages. You can also change it to $limitnum = 5 * $limit; if you want the server to do more work :)

    elseif ($ppage < $page - $limitnum || $ppage > $page + $limitnum){} // This statement bypasses all pages not 5 higher or 5 lower from the current page. If you want to make it more increase your limitnum. If I clicked on the 10th page, here's what the results would look like.

    back 5 6 7 8 9 10 11 12 13 14 15 Next

    Heres' the bottom portion of the script with the $limitnum and elseif statement put into place.

    $limitnum = 50;

    login or register to post comments

    The echo's above are empty by accident.

    Submitted by phpoo on July 16, 2002 - 14:00.

    The echo's above are empty by accident. This forum must have stripped them. Just notice where I made the additions and add them to your script.

    login or register to post comments

    Including code in comments

    Submitted by MartinB on July 16, 2002 - 14:27.

    If you'd like to include code in comments, then please:

    1. Escape the HTML entities
    2. Enclose longer snippets (ie if it's not inline in a paragraph) in &lt;pre&gt; tags

    login or register to post comments

    Gracias...

    Submitted by phpoo on July 16, 2002 - 15:22.

    Thanks for the heads up.

    login or register to post comments

    Using Strings

    Submitted by Machineman on September 8, 2002 - 20:23.

    This article may be of interest to everyone:
    http://www.zend.com/zend/tut/using-strings.php

    login or register to post comments

    Great stuff, it's been a big help

    Submitted by sadecu on May 23, 2003 - 08:40.

    Thanks, it just took me 15 mins to adapt it and it worked perfectly.

    login or register to post comments

    Big help saved me a lot of time

    Submitted by jlunn on June 19, 2003 - 10:38.

    I didn't need the "query thing" so I omitted it. I just displayed the data based on a standard query. Thanks again.

    login or register to post comments

    How 2 do this (|< << ... 21 22 23 24 25 ... >> >|)

    Submitted by WiseOne on October 17, 2003 - 10:01.

    the above tutorial was xcellent but i am facing 1 problem i.e., my search query returns 150 pages... how do i handle that??? something like this will do ( |< > >| ) how do i code it????

    login or register to post comments

    Turn into function??

    Submitted by mlie on September 9, 2004 - 17:07.

    I tried to use this for my page. But it's still not working.... I am using templates for my php page so I have to convert every echo's and I can't just close php tags and add html tags below it. Is there a way that I can turn this into a function??

    login or register to post comments

    Can someone help with the above code?

    Submitted by paulf on October 9, 2004 - 02:15.

    I have tried to use the above code for multiple pages with PHP but when i try to run the above code it is coming up up with the following error message

    Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/djfrap/public_html/index2.php on line 89

    my code in the section where there is an error is below // Now we can display results.

    $results = mysql_query("SELECT * FROM pet ORDER BY petName ASC LIMIT $page, $limit"); while($data = mysql_fetch_array($result)) - Line 89

    then i have put the usual code in betwen the

    {

    to excecute the output of the code with the field name.

    }

    i would really appreciate if someone could help me as i am trying to learn PHP in a short amount of time so i can move onto bigger and better things. Paul

    login or register to post comments

    This script is excellent

    Submitted by darrenevans on December 8, 2004 - 21:49.

    This script was just what I was looking for. I have adapted it extensively, but the old structure is there. I would like to thank the author for his valuable addition to the community. You have helped me a lot. I have added features to this script on my website. The address is www.secondhandonline.net, then click zum Verkauf (it's in German, but hopefully is self-expainatory). I hope it is moral to put this address here (more for you than me), apologies if not. I am happy to share any of the adapted code if you e-mail me (info@secondhandonline.net). Many thanks, Darren

    login or register to post comments

    Saved My Hide

    Submitted by blasterpaster on December 9, 2004 - 22:00.

    I have been a novice programmer for a few years now and I recently took on a project which was a little over my head, (I did NOT know it when I took on the job), and this article just saved my hide. Thank you soooo much...

    login or register to post comments

    i would like to know too

    Submitted by stuk on September 15, 2005 - 12:27.

    the above tutorial was xcellent but i am facing 1 problem i.e., my search query returns 150 pages... how do i handle that??? something like this will do ( |< > >| ) how do i code it????

    i want to know how to do that too!
    if i get 100+ pages it will be a great MESS in the page so i'd like to know how to code that...

    login or register to post comments

    Undefined

    Submitted by Slypig on February 7, 2006 - 02:09.

    if (!($limit)){ $limit = 10;} if (!($page)){ $page = 0;} returns Undefined variable for me on first search. Other than that, it works fine. Anybody else know how to fix this?

    login or register to post comments

    About the $Limit

    Submitted by GraveDigger on February 24, 2006 - 10:44.

    It would be nice if we change this

    if (!($limit)){ $limit = 10;} // Default results per-page.

    to

    $limit = 10; // Change the No. of results per-page as desired.

    This will also get rid of (limit=$limit) from all the query lines.

    Guess this will make the file 2~3 kb smaller. :-)

    login or register to post comments

    Thanks!

    Submitted by jurban on April 12, 2006 - 19:37.

    Easy to follow.... needs a few adjustments, but worked great! Thanks!!

    login or register to post comments

    Limiting the page results at the bottom

    Submitted by kingdavies on April 17, 2006 - 14:33.

    Can somebody please explain how to limit the page results at the bottom of the page; like phpoo has done unfortunately I didn't understand his post.

    login or register to post comments

    Limit page results at bottom

    Submitted by tinamar on April 22, 2006 - 15:14.

    I'm not sure if kingdavies still needs this, but I have a solution (it's not pretty, but it works). I'm not a very efficient coder -- I do what I can. This is what I did to limit my page displays. My total record count is around 2300. I show 150 records per page. I wanted only 10 page numbers to show at any given time. So, I added this above the loop that prints page links:

    // this checks to see if the current page is 10 or lower. You could use a calculation to get the value of your top page. In my case, I just hard coded the result: number of pages I want to see * numbers of records per page - number of records per page. In my case, 10 * 150 - 150 = 1350. If the current page is less than 1350, it sets the first page to "show" as 1 and the last page to show as 10.

    if (($page == 0) OR ($page < 1350)) {
    $firstshow = 1;
    $lastshow = 10;
    }
    // if the current page is higher than 10 the first page to show is set to the current page
    elseif ($page >= 1350) {
    $firstshow = ($page / 150) + 1;
    $lastshow = $firstshow + 10;
    // the last page to show is set to current plus 10 (above). Since that may actually be outside of the range of pages, I check (below). If the last page to show is equal to or greater than the total pages, the last page to show becomes the total pages
    if ($lastshow >= $pages) {
    $lastshow = $pages;
    }
    }

    Now, instead of using $i through $pages as your loop when printing pages, set $i to $firstshow and $pages to $lastshow. That limits your loop range to only the range of pages you want to display.

    I'm sure some easy tweaking could improve. The main annoyance is that once you get past page 10, you don't necessarily see 10 page links. For instance, my page creates a total of 16 pages. Because of my code, when I am on page 16, only page 16 shows -- you have to click "back" to get to page 15, on which two pages show: 15 and 16. I will be fixing this, but don't have time right now. Must finish other parts of this project and put this on the "polishing" list.

    I'm sure there's a better way -- but I'm a hack coder. Improvements are always welcome...

    login or register to post comments

    pages not working

    Submitted by bargain_newbie on June 21, 2006 - 22:22.

    Hi, newbie here. I have phpadmin on my computer and have been learning basic php/mysql. In the example above..I followed the entire code, made the necessary adjustments in connecting to the database, table, fields, etc. I can display the records with my desired limit just fine. But I can't make the page display the rest of the records if I hit the page numbers or "next" link. I didn't make any changes on this section, copied the whole thing. But it's not working. Any ideas why?

    login or register to post comments

    How i can do it with my script?

    Submitted by klawchi on June 23, 2006 - 09:27.

    Hi,

    I am not a programmer but i have good experience of programing, i have been studied but not working with programming.
    I am sitting 2 days to sort the MySQL results with paging,, but i failed :(
    This is my script:


    $where = " AND (";
    if ($sections != "") $where .= "sectionid IN (". $sections. ") ";
    if ($sections != "" && $categories != "" ) $where .= " OR ";
    if ($sections != "" && $categories != "" ) $where .= "cc.id IN (". $categories. ")";
    $where .= ") ";

    // query records
    $query = "SELECT a.*, cc.image AS image"
    . "\n FROM #__content AS a"
    . "\n INNER JOIN #__categories AS cc ON cc.id = a.catid"
    . "\n WHERE a.state = '1'"
    . $where
    . "\n AND ( publish_up = '0000-00-00 00:00:00' OR publish_up = '$now' )"
    . "\n AND published = '1'"
    . "\n ORDER BY publish_up DESC";

    $database->setQuery( $query );
    $rows = $database->loadObjectList();
    echo $database->getErrorMsg();

    Thanks

    login or register to post comments

    Limit number of pages

    Submitted by observer2574 on August 6, 2006 - 09:27.

    First off, I'd like to say thanks for the initial article on creating multiple pages. Worked very well for me. However, the dataset I'm working with returns in the region of 2800 results, with a fixed limit of 100 records per page. I've had a look at phpoo's code for limiting the number of displayed pages and I have to say I don't think it's correct. If I have misunderstood I apologise in advance, and I would be more than happy to be corrected. However, it has taken me a day to get this to work, so I thought I would share my experience!

    The logic is: if $ppage (which corresponds to $page, except on the first page) is less than $page-$limitnum OR is greater than $page+$limitnum then display a page. Well, if I add that in straight away I find that the wrong pages are returned. The code looks like this:

    for ($i=1; $i <= $pages; $i++) // loop through each page and give link to it.
    {
     $ppage = $limit*($i - 1);
     if ($ppage == $page){
     echo("<b>$i</b>\n");} // If current page don't give link, just text.

     elseif ($ppage <$page-$limitnum||$ppage>$page+$limitnum)
    //this is phpoo's code

    {echo("<a href=\"$PHP_SELF?page=$ppage&limit=$limit\">$i</a> \n");}
    }

    The condition is evaluated and only pages which are 'smaller' than (the current page - limitnum) or 'bigger' than (the current page + limitnum) are returned. In my code, with a limitnum of 300, this means that on the first page I get a result set like:

    1 5 6 7 8 9 10 11 12 13 etc ...

    If I click Next I get:

    back 2 6 7 8 9 10 11 12 13 etc ...

    Not right. After much experimentation I have found that the nearest solution is this:

    elseif ($ppage >$page-$limitnum&&$ppage<$page+$limitnum)

    This says: If the $ppage is greater than the current page - limitnum AND is smaller than the current page + limitnum, return pages. So if you imagine the current page being 900 (i.e. page 10 in my data set)and the limitnum being 500, we want to display pages greater than 400 (the page, 900, minus the limitnum, 500) and less than 1400.

    Although this works, it does mean that the number of displayed, numbered pages increases for the first few pages until there are 'x' pages either side of the current page. So with a limitnum of 500 and a limit of 100, on page 1 there are pages 1 to 5 displayed, by page 5 pages 1 to 9 are displayed, and from page 8 onwards the final total of four pages each side of the current page are displayed.

    There are probably other, better ways of doing it, and I may have misunderstood phpoo's code, but I thought I would share this to help any other php novices who might have been struggling like me!

    Thanks!

    login or register to post comments

    Wonderful Tutorial but REGISTER_GLOBALS problem

    Submitted by BluePhoenixNC on December 24, 2006 - 16:05.

    Thanks for putting it out ther to be used, I liked it from the get go and I had no problem whatsoever to implement and modify it to suit my needs, very well documented and easy to follow. However I came across one pitfall, and wonder if someone can help there, this code does not seem to work when REGISTER_GLOBALS is turned off, and I do not know how to fix it, except to enable them. Anyone has any ideas how to use the code without enabling the register_globals in php.ini ? Thanks

    login or register to post comments

    Sliding Window Like This

    Submitted by gtlitc on January 16, 2007 - 14:17.

    Big respect for the initial post. I have tweeked it so as to have a sliding window which is what I required.

    You get the idea.

    $showpages = 5;

    $winsize = ($showpages * $limit)-1; // Calculate the size of window.

    $wintemp = $page/$winsize;

    $wintail = intval($wintemp)*$winsize; // Set the tail pointer.

    $winhead = $wintail + $winsize; // Set the head pointer.

    elseif ($ppage < $wintail || $ppage > $winhead){}

    login or register to post comments

    Taking the Sitemap into Consideration

    Submitted by Brad Henry on January 17, 2007 - 18:58.

    This type of script can be helpful for sites that have thousands of dynamic pages including most ecommerce sites. By using the script above you can dynamically create a sitemap that limits the number of internal linking to a reasonable amount. Most search engines don't like to see more than 100 links per page so you can ultimately create a sitemap that connects your entire database in through a series pages using text based "next" and "previous" links.
    Thanks,
    Brad Henry

    login or register to post comments

    Jester uk, I managed to

    Submitted by Askim on March 21, 2007 - 03:31.

    Jester uk, I managed to adapt the script to my needs and it works great. Brad do you think that 100 is the optimal nuber of links per page when creating a sitemap. It seems to me that it's a bit to steep.

    login or register to post comments

    My possible messup, A possible solution.

    Submitted by Fisker on April 25, 2007 - 14:02.

    This script will not work in PHP5, Because all html-passings are sent into $_GET[] array.

    So $variable = $_GET[variable]
    This problem is easily solved,
    At the top of the code just add these lines.
    $limit = $_GET[limit];
    $page = $_GET[page];
    $query = $_GET[query];

    And the same for any other action that's being passed to the URL.

    Now, I'm not the most experienced programmer, So this might cause
    additional problems, But for now it seems to be working for me =)

    Great job jester, This script works great when tweaked!

    login or register to post comments

    Need Simple help

    Submitted by jirimail on May 1, 2007 - 13:44.

    Hey guys! Just wondering, could you pls help me with this script:

    if (!$q) $ddl->page("index.php?page="); else $ddl->page("index.php?q=$q&page=");

    It shows number of pages on my index site, however it goes into houndreds. I need to limit the number of shown pages to 10 and then just go 2-11 and 3-12.. hope you understand? Is there any easy fix this script? Thank you. Jiri

    login or register to post comments

    please kindly help me,..

    Submitted by dee2_dex11 on May 7, 2007 - 07:03.

    Hi. please kindly help me, i am a newbie for the php and MysQl and i would like to ask if you can help me where should i put code for the multiple pages in my code, and which code, and explain why?

    login or register to post comments

    Slight problem

    Submitted by nate189 on May 16, 2007 - 04:19.

    Hello,

    I have configured this script on my server, it appears to be working fine, however I am having an issue with the pictures not changing from page to page. Every page has the same pictures on it.

    I am trying to configure a similar setup as the example here: http://hemsidor.torget.se/users/n/nozick/diverse/galleri.jpg If somebody could provide me with this working example I would appreaciate it.

    My script is able to read the database and generate page numbers based on the number of results per page, however the results are the same for every page.

    For example: I have pictures A, B, C, D, E and F. Using 5 results per page. Page 1 displays: A, B, C, D, E Page 2 and up displays: A, B, C, D, E

    F and higher are not displayed unless the max results is increased.

    What to do? I've read some comments about the PHP version being an issue, I have attempted this on PHP 4.x and 5.x with the same results.

    Please advise. Many thanks.

    login or register to post comments

    I'm having some trouble here

    Submitted by mossberg on September 30, 2007 - 08:09.

    I have a bit more complicated variation of a multiple pages system where I have two queries from two tables in a database - one query contains excursion information, the other one contains the pictures for the corresponding excursion while the excursion table primary key is a foreign key in the pictures table. Now I'm looking for a good way to associate pictures with their corresponding excursions in the page code itself. Please take a look at my code and give suggestions because that's a bit more difficult than I can manage. Keep in mind that I'm sorting the excursions by price in order from most expensive to least expensive (for testing purposes). The arrays look like that: the name of this array i'm using in the code is $arr[cell index][database field name]
    Array (
    [0] => Array (
       [0] => 6
       [exc_id] => 6
       [1] => 0
       [spec] => 0
       [2] => Europe
       [continent] => Europe
       [3] => Romania
       [country] => Romania
       [4] => Excursions
       [type] => Excursions
       [5] => Bucharest Excursion
       [name] => Bucharest Excursion
       [6] => 08.13.2013
       [date] => 08.13.2013
       [7] => Bucharest
       [destination] => Bucharest
       [8] => Bucharest Excursion Description
       [descr] => Bucharest Excursion Description
       [9] => Bucharest Excursion Includes
       [includes] => Bucharest Excursion Includes
       [10] => 350
       [price] => 350
       [11] => Bucharest Excursion Does Not Include
       [notinc] => Bucharest Excursion Does Not Include
       [12] => Bucharest Excursion Notes
       [notes] => Bucharest Excursion Notes
       [13] => Bucharest Excursion Additional Payment
       [dopl] => Bucharest Excursion Additional Payment )
    That's the first entry [0], the next one [1] is a similar array with the same cells and different info. The Array for the pictures of the excursion with the corresponding excursion id (in this case exc_id 6) looks like that: this array is referred to in the code as $arr_pics
    [5] => Array (
      [0] => 6
      [pic_id] => 6
      [1] => 6
      [exc_id] => 6
      [2] => ../excursions/1191012222_1.jpg
      [pic_address] => ../excursions/1191012222_1.jpg )
    The part of the code where I'm trying to dynamically display the correct excursions with the correct pictures for them:
    <div id="content">
    <div id="preview">
    <h1><a href="excursion.php?id=<?php
    /*Look here, that's where I suspect one of my mistakes: the variable $latest_added[0] contains the result of a mysql_query(); that takes the highest excursion id from the excursion table. I'm substracting 1 from it, so that excursion id 7 corresponds to the array cell 6 when I'm using this number later in the code: */

    $id = $latest_added[0]-1; echo $arr[$id]['exc_id']; ?>"><?php echo $arr[$id]['name']; ?></a></h1>
    <a href="excursion.php?id=<?php echo $arr[$id]['exc_id']; ?>"><img src="<?php

    // That's just to give you an idea, obviously I need to make this thing work dynamically while the excursion html code is generated by a loop.
     $pic_id1 = $arr[6]['exc_id']-1;
     $pic_id2 = $arr[5]['exc_id']-1;
     $pic_id3 = $arr[4]['exc_id']-1;
     $pic_id4 = $arr[3]['exc_id']-1;
     $pic_id5 = $arr[2]['exc_id']-1;
     $pic_id6 = $arr[1]['exc_id']-1;
     $pic_id7 = $arr[0]['exc_id']-1;

     echo $arr_pics[$pic_id1]['pic_address']; ?>" alt="<?php echo $arr[$id]['destination']; ?> preview" /></a>

    <p></p>
    </div>
    <div id="rpanel">
    <p></p>
    <h2><a href="excursion.php?id=<?php echo $arr[$id]['exc_id']; ?>"><?php echo $arr[$id]['destination']; ?></a></h2>
    <ul id="descr">
    <li>
    <p class="date"><?php echo $arr[$id]['country']; ?></p>
    <p><a href="excursion.php?id=<?php echo $arr[$id]['exc_id']; ?>"><?php echo $arr[$id]['type']; ?></a></p>
    </li>
    <li>
    <p class="date"><?php echo $arr[$id]['type']; ?></p>

    <p><a href="excursion.php?id=<?php echo $arr[$id]['exc_id']; ?>">Other Information</a></p>
    </li>
    </ul>
    </div>
    <div class="items1">
    <div>
    <h2><a href="excursion.php?id=<?php $id--; echo $arr[$id]['exc_id']; ?>"><?php echo $arr[$id]['name']; ?></a></h2>
    <a href="excursion.php?id=<?php echo $arr[$id]['exc_id']; ?>"><img src="<?php echo $arr_pics[$pic_id2]['pic_address']; ?>" alt="<?php echo $arr[$id]['destination']; ?>" /></a>
    <p><?php echo $arr[$id]['price']; echo $currency?></p>

    </div>
    <div>
    <h2><a href="excursion.php?id=<?php $id--; echo $arr[$id]['exc_id']; ?>"><?php echo $arr[$id]['name']; ?></a></h2>
    <a href="excursion.php?id=<?php echo $arr[$id]['exc_id']; ?>"><img src="<?php echo $arr_pics[$pic_id3]['pic_address']; ?>" alt="<?php echo $arr[$id]['destination']; ?>" /></a>
    <p><?php echo $arr[$id]['price']; echo $currency?></p>

    </div>
    <div>
    <h2><a href="excursion.php?id=<?php $id--; echo $arr[$id]['exc_id']; ?>"><?php echo $arr[$id]['name']; ?></a></h2>
    <a href="excursion.php?id=<?php echo $arr[$id]['exc_id']; ?>"><img src="<?php echo $arr_pics[$pic_id4]['pic_address']; ?>" alt="<?php echo $arr[$id]['destination']; ?>" /></a>
    <p><?php echo $arr[$id]['price']; echo $currency?></p>
    </div>
    <div>
    <h2><a href="excursion.php?id=<?php $id--; echo $arr[$id]['exc_id']; ?>"><?php echo $arr[$id]['name']; ?></a></h2>
    <a href="excursion.php?id=<?php echo $arr[$id]['exc_id']; ?>"><img src="<?php echo $arr_pics[$pic_id5]['pic_address']; ?>" alt="<?php echo $arr[$id]['destination']; ?>" /></a>
    <p><?php echo $arr[$id]['price']; echo $currency?></p>
    </div>
    <div>
    <h2><a href="excursion.php?id=<?php $id--; echo $arr[$id]['exc_id']; ?>"><?php echo $arr[$id]['name']; ?></a></h2>
    <a href="excursion.php?id=<?php echo $arr[$id]['exc_id']; ?>"><img src="<?php echo $arr_pics[$pic_id6]['pic_address']; ?>" alt="<?php echo $arr[$id]['destination']; ?>" /></a>
    <p><?php echo $arr[$id]['price']; echo $currency?></p>
    </div>
    <div>
    <h2><a href="excursion.php?id=<?php $id--; echo $arr[$id]['exc_id']; ?>"><?php echo $arr[$id]['name']; ?></a></h2>
    <a href="excursion.php?id=<?php echo $arr[$id]['exc_id']; ?>"><img src="<?php echo $arr_pics[$pic_id7]['pic_address']; ?>" alt="<?php echo $arr[$id]['destination']; ?>" /></a>
    <p><?php echo $arr[$id]['price']; echo$currency?></p><br />
    </div>
    </div>
    <div class="items1">
    <?php echo '<a>'.$arr[0]['type']; ?>: <strong><?php echo $first; ?></strong> - <strong><?php echo $last;?></strong> of <strong><?php echo $numrows; ?></strong></a> ?>
    To make it a bit easier for you, this the code from my head section, where I make the sql queries:
    ...
    ///Multiple pages support

    if (!($limit)){
         $limit = 7;} // Default results per-page.

    if (!($page)){
         $page = 0;} // Default page value.

    ///End. Continues after the queries

      $select_latest = "SELECT MAX(`price`) FROM `kartagotours_bg_-_".$_GET[lang]."`.`excursion`;";
      $result_latest = mysql_query($select_latest);
      $latest_added = mysql_fetch_array($result_latest);
      $id = $latest_added[0];
      $final_latest = $latest_added[0] - 7;
      
      $query = "SELECT * FROM `kartagotours_bg_-_".$_GET[lang]."`.`excursion` WHERE `type` = '".$excursions."' ORDER BY `price` DESC LIMIT ".$page.", ".$limit.";";
      $result = mysql_query($query);
      $arr = mysql_fetch_rowsarr($result); /* This mysq_fetch_rowsarr() is a function that helps me recover results from a query made for more than one database row. It works much better than the usual mysql_fetch_array() because it creates one big array for all results which contains every row returned in its separate sub-array */
      
        $query_pics = "SELECT * FROM `kartagotours_bg_-_".$_GET[lang]."`.`excursion_pics` WHERE `exc_id` IN (SELECT `exc_id` FROM `kartagotours_bg_-_".$_GET[lang]."`.`excursion` WHERE `type` = '".$excursions."');";

      $result_pics = mysql_query($query_pics);
      $arr_pics = mysql_fetch_rowsarr($result_pics);

    ///Multiple pages support continues here
    ...
    Any help is greatly appreciated :)

    login or register to post comments

    Progress made :)

    Submitted by mossberg on September 30, 2007 - 09:10.

    I just solved the most serious part of the problem. It's always like that - when you explain it to someone else, it helps you understand it better yourself :) So the problem was in the $id = $latest_added[0]-1; I found out that if $id will be showing my loop which array index to look at (as in $arr[$id][exc_id]), I don't need to give it any other value than 0 and simply increment it with every loop iteration :) More simple than I thought. So now it works excellent with one little thing remaining: I can't write a loop that works well with me. Take a look:
    <div id="content">
    <div id="preview">
    <h1><a href="excursion.php?id=<?php $id = 0; /* ***Change made here*** */; echo $arr[$id]['exc_id']; ?>"><?php echo $arr[$id]['name']; ?></a></h1>
    <a href="excursion.php?id=<?php echo $arr[$id]['exc_id']; ?>">

    <img src="<?php $pic_id = $arr[$id]['exc_id']-1; /* *** Change made here. I'm substracting one in order to get the array cells (which start from 0) to work in sync with the exc_ids (which start from 1)***  */ echo $arr_pics[$pic_id]['pic_address']; ?>" alt="<?php echo $arr[$id]['destination']; ?> preview" /></a>
    <p></p>
    </div>
    <div id="rpanel">
    <p></p>
    <h2><a href="excursion.php?id=<?php echo $arr[$id]['exc_id']; ?>"><?php echo $arr[$id]['destination']; ?></a></h2>
    <ul id="descr">
    <li>
    <p class="date"><?php echo $arr[$id]['country']; ?></p>
    <p><a href="excursion.php?id=<?php echo $arr[$id]['exc_id']; ?>"><?php echo $arr[$id]['type']; ?></a></p>
    </li>
    <li>
    <p class="date"><?php echo $arr[$id]['type']; ?></p>

    <p><a href="excursion.php?id=<?php echo $arr[$id]['exc_id']; ?>">Other Information</a></p>
    </li>
    </ul>
    </div>
    <div class="items1">
    here is where I need a loop which loops this code:
    <div>
    <h2><a href="excursion.php?id=<?php $id++; echo $arr[$id]['exc_id']; ?>"><?php echo $arr[$id]['name']; ?></a></h2>
    <a href="excursion.php?id=<?php echo $arr[$id]['exc_id']; ?>"><img src="<?php echo $arr_pics[$pic_id]['pic_address']; ?>" alt="<?php echo $arr[$id]['destination']; ?>" /></a>
    <p><?php echo $arr[$id]['price']; echo $currency?></p>
    </div>
    Until it loops it a total of 6 times and increments $pic_id every time in order to display excursion pics with indexes from 2 to 7 (1 being displayed in the beginning, before the loop starts) The rest of my code doesn't need changes for now. So can anyone give me an idea?

    login or register to post comments

    Solution found

    Submitted by mossberg on September 30, 2007 - 10:06.

    The needed loop was:
    <?php
    //Instead of $a you can use directly the $id variable
    for ($a = 1; $a <=6; $a++) {
        
    $id++;
        
    $pic_id = $arr[$id]['exc_id']-1;
        echo
    '<div>';
        echo
    '<h2><a href="excursion.php?id='.$arr[$id]['exc_id'].'">'.$arr[$id]['name'].'</a></h2>';
        echo
    '<a href="excursion.php?id='.$arr[$id]['exc_id'].'"><img src="'.$arr_pics[$pic_id]['pic_address'].'" alt="'.$arr[$id]['destination'].'" /></a>';
        echo
    '<p>'.$arr[$id]['price'].$currency.'</p>';
        echo
    '</div>';


    }
    ?>
    Hope all this helps somebody in the future. Coordinating two sql queries to display results dynamically with php.

    login or register to post comments

    The access keys for this page are: ALT (Control on a Mac) plus:

    evolt.orgEvolt.org is an all-volunteer resource for web developers made up of a discussion list, a browser archive, and member-submitted articles. This article is the property of its author, please do not redistribute or use elsewhere without checking with the author.