PHP

Step 3: Adding Page Numbers

In this section, we extend the browse( ) function to produce page numbers to permit direct access to the pages, removing the need for the user to repeatedly click the Previous or Next links to find a particular page or row. The extended fragment of browse( ) that produces the page links is shown in Example 5-11.

Example 5-11. Adding direct page access to browse( )
// (7a) Previous link code goes here
// Output the page numbers as links
// Count through the number of pages in the results
for($x=0, $page=1;
    $x<$rowsFound;
    $x+=ROWS, $page++)
   // Is this the current page?
   if ($x < $rowOffset ||
       $x > ($rowOffset + $numRowsToFetch - 1))
      // No, so print out a link
      echo "<a href=\"" . $scriptName .
           "?offset=" . rawurlencode($x) .
           "&amp;" . $browseString .
           "\">" . $page  . "</a> ";
      else
         // Yes, so don't print a link
         echo $page  . " ";
// (7b) Next link code goes here

The page number code consists of a for loop that works as follows:

  • The loop begins counting rows using the variable $x-starting at row zero-and pages using $page, starting on page one. The loop finishes when $x is equal to the number of rows in the query result set.

  • In the body of the loop, if the row $x isn't on the current page displayed in the HTML <table>, an embedded link is output that is marked with the page number $page. The link is to the script resource $scriptName, with the parameters in $browseString and an offset of the current value of $x. The current value of $x is the first row on the page numbered $page. Clicking on the link requests the script again and produces the results for $page that begin with the row with an offset of $x.

    For example, if $x is row 220, and the $page is 11, the embedded link output by the code fragment is:

    <a href="example.5-11.php? offset=220&amp;regionName=Margaret%20River">11</a>
    
  • If $x is a row on the currently displayed page, the code outputs the page number without the embedded hypertext link.

The case study of a generic browse( ) function is now complete. Additional features can be added, as discussed briefly in the next section.

What's Missing from the Previous and Next Browser

Features that aren't described here but could be incorporated in the browse( ) function include:

  • Configurable colors for columns, headers, and links.

  • Configurable column alignment and fonts.

  • Other layouts, such as horizontal table-based layouts. See the winestore Hot New Wines panel as an example.

  • Embedding of links in the body of the <table> so that other queries can be run by clicking on data in the <table>. Our customized version for the winestore that is described in Chapter 13 supports this feature.

  • Spreadsheet-like features, such as the ability to click on a column heading to sort the data by that column.