HomePHP Page 4 - Previous or Next? Paginating Records with PHP, part 4
Paging MySQL records: putting the "Pager" class into action - PHP
In the fourth and final article in our series about paginating records with PHP, we will look at the source code for the "pager" PHP class we developed in part three, and show several examples to demonstrate possible uses in production environments.
Before showing any examples, a disclaimer is in order. Since we need to connect to the MySQL server, I will use a hypothetical MySQL class to perform the server connection. So, if you're seated on the procedural chair, don't worry. I'll take a look at that approximation too. Having said that, let's show the first example, first defining a simple default template file, as listed below:
That's all that we need to format the result set. Definitely, you'll agree that this template file is very simple. Now, let's continue defining some CSS rules, in order to style the records and the paging links:
Finally, let's implement our "Pager" class, including the paging class file, a MySQL abstraction class, and the instantiation of the corresponding objects:
<?php // include class files require_once('pagerclass.php'); require_once('mysqlclass.php');
// instantiate a new MySQL object $db=&new MySQL('dbhost','username','password','songs');
// instantiate a new Pager object $pager=&new Pager($db->getConnectionId(),'SELECT * FROM songs','paginglinks',5);
// display paginated result set echo $pager->displayRecords($_GET['page']);
?>
Notice from the above example, that I've specified the display of five records per page, feeding the class with that incoming value.
For those Web developers connecting to MySQL using a procedural method, the above code can be rewritten as follows:
<?php // include the pager class require_once('pagerclass.php');
// connect to MySQL $conId=@mysql_connect('dbhost','username','password') or die ('Error connecting to the server: '.mysql_error());
// select database mysql_select_db('songs') or die ('Error selecting database');
// instantiate a new pager object $pager=&new Pager(&$conId,'SELECT * FROM songs','paginglinks',5);
// display records and paging links echo $pager->displayRecords($_GET['page']);
?>
Whatever method you use to connect to MySQL, the rendered output would look similar to this:
Not too bad, eh? Please notice how we've formatted database records and paging links, simply by using a three line template file. However, this is not the end. What if we change our mind and want to use another template file to build a different look and feel? Just go to the next page to find out more.