PHP, Templating, MySQL and Page counting



I'm working on an application for one of my employers. This application reads thousands of rows of data and renders it to the browser. Unfortunately with thousands of rows of data page load times are huge, the server can run out of memory, and other irritating problems.

So I began investigating page numbering for this problem. It was quite easier than I imagined. It is as easy as you using LIMIT in your SQL statement, with the FROM parameter, ex:

select * from some_table limit 1, 30

In the above the sql will only return 30 results/rows, starting with the first. I then created a template function that takes three parameters: current page, total pages, and the link to be used as the base for the navigation:

  function buildPageLinks($page, $totalPages, $link) {
       $pageLink = "";
    if($page > 1){
        $prev = ($page - 1);
        $pageLink = "<a href=\"".$link."&page=$prev\"><<Previous</a> ";
    }
    
    for($i = 1; $i <= $totalPages; $i++){
        if(($page) == $i){
            $pageLink .="$i ";
        } else {
            $pageLink .= "<a href=\"".$link."&page=$i\">$i</a> ";
        }
    }

 
    if($page < $totalPages){
          $next = ($page + 1);
          $pageLink .= "<a href=\"".$link."&page=$next\">Next>></a>";
    }
      return $pageLink;
 
   }

    Hope this helps you build your navigation links.